Home > Article > Web Front-end > How to make checkbox read-only in jquery
Two read-only methods: 1. Use attr() to add the disabled attribute to the check box, the syntax is "$("input[type='checkbox']").attr("disabled",true );"; 2. Use click() to set the checkbox status without changing the checkbox state when clicked. The syntax is "$("input[type='checkbox']").click(function(){return false;})" .
The operating environment of this tutorial: windows7 system, jquery3.6.0 version, Dell G3 computer.
When it comes to read-only, it is easy to think of using the readonly attribute, but for checkboxes, this attribute is different from the expected effect. The reason is that the readonly attribute is associated with the value attribute of the page element (such as textbox, the text content of the input box cannot be modified when readonly is set), and checking/unchecking the checkbox does not change its value attribute, only a checked state. So for the checkbox, if readonly is set, it can still be checked/cancelled.
<input type="checkbox" readonly>option a<br> <input type="checkbox" readonly>option b<br> <input type="checkbox" readonly>option c<br>
But similar to readonly, there is also a disabled attribute. The function of this attribute is to set the page element to be unavailable, that is, no interactive operations can be performed (including unmodifiable value attribute, unmodifiable checked status, etc.).
<input type="checkbox" disabled>option a<br> <input type="checkbox" disabled>option b<br> <input type="checkbox" disabled>option c<br>
Method 1:
In jquery, you can use attr() to add disabled to the checkbox (checkbox) Attribute
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="js/jquery-3.6.0.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { $("input[type='checkbox']").attr("disabled", true); }); }); </script> </head> <body> <input type="checkbox">option a<br> <input type="checkbox">option b<br> <input type="checkbox">option c<br> <br> <button>让复选框只读</button> </body> </html>
Method 2:
If you use the disabled="disabled" attribute, the checkbox will turn gray. Users may dislike the effect, or they can set the checkbox to not change state when clicked.
$(document).ready(function() { $("button").click(function() { $("input[type='checkbox']").click( function(){return false;} ); }); });
Recommended related video tutorials: jQuery Tutorial (Video)
The above is the detailed content of How to make checkbox read-only in jquery. For more information, please follow other related articles on the PHP Chinese website!