No, input checkboxes can't be readonly.
But you can make them readonly with javascript!
Add this code anywhere at any time to make checkboxes readonly work as assumed, by preventing the user from modifying it in any way.
jQuery(document).on('click', function(e){
// check for type, avoid selecting the element for performance
if(e.target.type == 'checkbox') {
var el = jQuery(e.target);
if(el.prop('readonly')) {
// prevent it from changing state
e.preventDefault();
}
}
});
input[type=checkbox][readonly] {
cursor: not-allowed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" checked readonly> I'm readonly!</label>
You can add this script at any time after jQuery has loaded.
It will work for dynamically added elements.
It works by picking up the click event (that happens before the change event) on any element on the page, it then checks if this element is a readonly checkbox, and if it is, then it blocks the change.
This solution should be very efficient and be availble before the page finished loading when the same document click event listener is re-used to handle all the events.
Here's another example using vanilla js
document.addEventListener('click', function(e) {
// Check if the clicked element is a checkbox
// Check if the checkbox is read-only
if (e.target.type === 'checkbox' && e.target.getAttribute('readonly') !== null) {
// Prevent it from changing state
e.preventDefault();
}
});
input[type=checkbox][readonly] {
cursor: not-allowed;
}
<label><input type="checkbox" checked readonly> I'm readonly!</label>
Keep in mind that according to html5, having a readonly
attribute is not strictly valid on an input
with type checkbox
(despite working in all browsers and search engines don't care), feel free to use data-readonly
instead of readonly
if you care about that.
readonly
)readonly
! Why then this attribute would exist!readonly
is only a client-side attribute to help a browser properly render a site and then construct the correct request from it. The server cannot and should not know about thereadonly
attribute of the rendered page. It must assume the request came from anywhere (and possibly with malicious intentions); never rely on user-provided input. Still, why send a checkbox's value which you cannot edit in a request (if you set the value before rendering, you already know the value when the request is submitted, so there's no need to transmit it in the request)readonly
attribute exists there for some reason. It has certainly nothing to do with server side implementation. But it is there to tell the user "Hey! This value is being assumed here, and/but you cannot change this."