HTML DOM Input Password maxLength Property


The HTML DOM Input Password maxlength property is used for setting or returning the maxlength attribute of the input password field. The maxLength property specifies the maximum number of characters you can type in a password field.

Syntax

Following is the syntax for −

Setting the maxLength property −

passwordObject.maxLength = integer

Here, integer specifies the maximum number of characters that can be typed in the password field.

Example

Let us look at an example for the maxLength form property −

<!DOCTYPE html>
<html>
<body>
<h1>Input Password maxLength Property</h1>
Password: <input type="password" id="PASS" maxLength="5">
<p>Increase the maximum number of characters to be entered for the above field by clicking below button</p>
<button onclick="changeMax()">CHANGE LENGTH</button>
<p id="Sample"></p>
<script>
   function changeMax() {
      document.getElementById("PASS").maxLength = "15";
      document.getElementById("Sample").innerHTML = "Maximum number of characters are now increased to 15";
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the CHANGE LENGTH and entering more characters −

In the above example

We have first created an input password field with id “PASS” and having its maxLength attribute value set to 5. This means only 5 characters can be entered in this field.

Password: <input type="password" id="PASS" maxLength=”5”>

We have then created a button CHANGE LENGTH that will execute the changeMax() method when clicked by the user −

<button type="button" onclick="changeMax()">CHANGE LENGTH</button>

The changeMax() method uses the getElementById() method to get the input field with type password and sets it maxLength property to 15. We then show this change by displaying a message in the paragraph with id “Sample” using its innerHTML property −

function changeMax() {
   document.getElementById("PASS").maxLength = "15";
   document.getElementById("Sample").innerHTML = "Maximum number of characters are now increased to 15";
}
raja
Published on 09-Aug-2019 14:28:32
Advertisements