HTML DOM Input Password defaultValue Property


The HTML DOM Input Password defaultValue property is used for setting or getting the defaultValue of a password field. The defaultValue of an element is the value assigned to the value attribute. The difference between value property and defaultValue property is that the defaultValue property retains the original default value specified while the value property change based on the user input in the input field.

Syntax

Following is the syntax to set the defaultValue property −

passwordObject.defaultValue = value

Here, “value” is the password field default value.

Example

Let us look at an example for the Input Password defaultValue property −

<!DOCTYPE html>
<html>
<body>
<h1>Input Password defaultValue Property</h1>
Password: <input type="password" id="PASS" value="abcd123">
<p>Change the above password field default value by clicking on the CHANGE button</p>
<button type="button" onclick="changeDefault()">CHANGE</button>
<p id="Sample"></p>
<script>
   function changeDefault() {
      document.getElementById("PASS").defaultValue="Password1234";
      var P=document.getElementById("PASS").defaultValue;
      document.getElementById("Sample").innerHTML = "Default value has been changed from abc123 to "+P ;
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the CHANGE button −

In the above example −

We have first created a password input field with id “PASS” and value=”abcd123”.

Password: <input type="password" id="PASS" value="abcd123">

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

<button type="button" onclick="changeDefault()">CHANGE</button>

The changeDefault() method uses the getElementById() method to get the input field with type password and sets it defaultValue property to “Password123”. We then get the defaultValue property of the input with type password by again using the getElementById() method and assigning it to variable P. This variable is then displayed in the paragraph with id “Sample” using the innerHTML property of the paragraph −

function changeDefault() {
   document.getElementById("PASS").defaultValue="Password1234";
   var P=document.getElementById("PASS").defaultValue;
   document.getElementById("demo").innerHTML = "Default value has been changed from abc123 to "+P ;
}
raja
Published on 09-Aug-2019 10:46:09
Advertisements