Get the App
SLTechnology News&Howtos  ›  Development  › 

How to make input not editable by javascript

Shulou Source: shulou.com Published: 2022-05-31 23:35:18 11月02日 Update

This article mainly explains "javascript how to set input non-editable", the content of the article is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "javascript how to set input non-editable" bar!

Methods: 1, using disabled attribute setting, syntax is "element object. Setting = true"; 2, using setAttribute () method and readOnly attribute setting, syntax is "element object .setAttribute (" readOnly ", true)".

The operating environment of this tutorial: windows10 system, javascript1.8.5 version, Dell G3 computer.

How to make input non-editable by javascript

There are two ways to make input uneditable.

1. Make use of disabled attribute

The disabled property is a Boolean property.

The disabled attribute specifies the elements that should be disabled.

Disabled input elements are unavailable and unclickable.

2. Using readonly attribute and setAttribute method

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

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

The readonly attribute prevents the user from modifying the value until certain conditions are met (such as selecting a check box). Then, you need to use JavaScript to eliminate the readonly value and switch the input field to editable state.

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

The syntax is:

ElementNode.setAttribute (name,value)

Examples are as follows:

123 var btn1 = document.getElementById ('btn1'); btn1.onclick = function () {var txt = document.getElementById (' txt'); txt.disabled = true;} var btn1 = document.getElementById ('btn2'); btn1.onclick = function () {var txt = document.getElementById (' txt1') Txt.setAttribute ("readOnly", true);

Output result:

Thank you for reading, the above is the content of "javascript how to set input non-editable". After the study of this article, I believe you have a deeper understanding of how javascript sets input non-editable, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Attributes methods elements fields syntax learning content objects users switches inputs names that is Boolean ideas situations copies tutorials text articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Xiaomi Huawei Linux Redmi