Home >Web Front-end >Front-end Q&A >How to make input non-editable in javascript

How to make input non-editable in javascript

WBOY
WBOYOriginal
2022-04-11 11:41:236820browse

Method: 1. Use the disabled attribute setting, the syntax is "element object.disabled = true"; 2. Use the setAttribute() method and readOnly attribute setting, the syntax is "element object.setAttribute("readOnly", true)".

How to make input non-editable in javascript

The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.

How to set input to be non-editable in javascript

There are two ways to set input to be non-editable.

1. Use the disabled attribute

The disabled attribute is a Boolean attribute.

The disabled attribute specifies which elements should be disabled.

Disabled input elements are unusable and unclickable.

2. Use the readonly attribute and setAttribute method

The readonly attribute specifies that the input field is read-only.

Read-only fields cannot be modified. However, users can still tab to the field and select or copy its text.

The readonly attribute prevents users from modifying the value until certain conditions are met (such as a checkbox being selected). Then, you need to use JavaScript to eliminate the readonly value and switch the input field to an editable state.

The setAttribute() method is used to add a new attribute with a specified name and rule, or set an existing attribute to a specified value

The syntax is:

elementNode.setAttribute(name,value)

The example is as follows:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>123</title> 
</head>
<body>
<input id="txt" type="text" >
    <input id="btn1" type="button" value="利用disabled不可编辑">
<input id="txt1" type="text" >
    <input id="btn2" type="button" value="利用readOnly不可编辑">
 <script> 
        var btn1 = document.getElementById(&#39;btn1&#39;);
        btn1.onclick = function () {
            var txt = document.getElementById(&#39;txt&#39;);
            txt.disabled = true;
        }
        var btn1 = document.getElementById(&#39;btn2&#39;);
        btn1.onclick = function () {
            var txt = document.getElementById(&#39;txt1&#39;);
            txt.setAttribute("readOnly", true);
        }
    </script>
</body>
</html>

Output result:

How to make input non-editable in javascript

##[Related recommendations:

javascript video tutorial, webfrontend

The above is the detailed content of How to make input non-editable in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn