HTML DOM Input Password readOnly property


The HTML DOM Input Password readOnly property is used for setting or returning whether the input password field is read-only or not. The readOnly property makes the element non-editable but it can still be focused by tab or by clicking. If there is a default value inside a read-only element then it is sent to server on submit.

Syntax

Following is the syntax for −

Set the readOnly property −

passwordObject.readOnly = true|false

Here, true represents the password field is read only while false represents otherwise. The readOnly property is set to false by default.

Example

Let us look at an example for the password readOnly property −

<!DOCTYPE html>
<html>
<body>
<h1>password readOnly property</h1>
Password: <input type="password" id="PASS1" >
<p>Change the readOnly property of the above field by clicking the below button</p>
<button onclick="changeRead()">CHANGE</button>
<script>
   function changeRead() {
      document.getElementById("PASS1").readOnly = true;
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the CHANGE button. Now you won’t be able to type inside the input password box −

In the above example −

We have first created an input password field with id “PASS1”.

Password: <input type="password" id="PASS1">

We then created a button CHANGE that will execute the changeRead() method on being clicked by the user −

<button onclick="changeRead()">CHANGE</button>

The changeRead() method uses the getElementById() method to get the input element with type password. It then set its readOnly property to true. This means we cannot enter text into the password field now but it still can be focused. The text inside is sent to the server on clicking the submit button −

function changeRead() {
   document.getElementById("PASS1").readOnly = true;
}

Updated on: 22-Aug-2019

93 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements