Javascript Reference - HTML DOM Input Text maxLength Property








The maxLength property sets or gets the maxlength attribute of a text field.

The maxLength attribute specifies the maximum number of characters allowed in a text field.

Browser Support

maxLength Yes Yes Yes Yes Yes

Syntax

Return the maxLength property.

var v = textObject.maxLength 

Set the maxLength property.

textObject.maxLength=number 




Property Values

Value Description
number Set the maximum number of characters allowed in the text field

Return Value

A Number type value representing the maximum number of characters allowed in the text field.

Example

The following code shows how to set the maximum number of characters allowed in a text field.


<!DOCTYPE html>
<html>
<body>
Name: <input type="text" id="myText">
<button onclick="myFunction()">test</button>
<script>
function myFunction() {<!--from  w w  w .  j a va2  s. c  o m-->
    document.getElementById("myText").maxLength = "4";
}
</script>
</body>
</html>

The code above is rendered as follows:





Example 3

The following code shows how to get the maximum number of characters allowed in a specific text field.


<!DOCTYPE html>
<html>
<body>
<!--  w w w. ja  v a2 s. co  m-->
Name: <input type="text" id="myText" maxlength="30">
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {
    var x = document.getElementById("myText").maxLength;
    document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>

The code above is rendered as follows: