Home > Article > Web Front-end > How to set input box to read-only in javascript
Setting method: 1. Use the "document.getElementById(id)" statement to obtain the input element object according to the specified id value; 2. Use the "input object.setAttribute("readOnly", true)" statement to obtain the input element Add read-only style.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
In JavaScript, if you want to set the input box to read-only, you only need to use the setAttribute() method to add the read-only attribute --readOnly to the input element.
The setAttribute() method adds the specified attribute and assigns it the specified value.
Grammar:
element.setAttribute(attributename,attributevalue)
Example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <input type="text" id="text" /><br><br> <input type="button" value="设为只读" id="btn" /> <script> function my(id) { return document.getElementById(id); } my("btn").onclick = function() { my("text").setAttribute("readOnly", true); } </script> </body> </html>##[Related recommendations:
The above is the detailed content of How to set input box to read-only in javascript. For more information, please follow other related articles on the PHP Chinese website!