Two implementation methods: 1. Use attr() to add the readonly attribute to the input element, and set the attribute value to "readonly", the syntax is "$("input").attr("readonly"," readonly");". 2. Use prop() to add the readonly attribute to the input element, and set the attribute value to "true", using the syntax "$("input").prop("readonly",true);".
The operating environment of this tutorial: windows7 system, jquery3.6.0 version, Dell G3 computer.
If you want to make the input read-only, just add the read-only attribute (readonly) to the input element.
Therefore, using jquery to change the input to a read-only state is converted to using jquery to add the readonly attribute to the input element.
There are two implementation methods:
Use attr()
Use prop()
1. Use attr() to set the read-only status of the input element
<!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").attr("readonly","readonly"); }); }); </script> <style type="text/css"> .intro { font-size: 120%; color: red; } </style> </head> <body> <input type="text" value="hello"/><br /><br /> <button>给input添加只读属性</button> </body> </html>
2. Use prop() Set the read-only status of the input element
<!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").prop("readonly",true); }); }); </script> <style type="text/css"> .intro { font-size: 120%; color: red; } </style> </head> <body> <input type="text" value="hello"/><br /><br /> <button>给input添加只读属性</button> </body> </html>
Instructions:
In fact, the prop() method and the attr() method Similar, both are used to get or set the HTML attributes of elements, but there are essential differences between the two.
jQuery official recommendation: For attributes with two values of true and false, such as checked, selected, disabled, etc., it is recommended to use the prop() method to operate, while for other attributes it is recommended to use the attr() method. to operate.
[Recommended learning: jQuery video tutorial, web front-end video]
The above is the detailed content of How to change input to read-only status in jquery. For more information, please follow other related articles on the PHP Chinese website!