Javascript Reference - HTML DOM Input Search maxLength Property








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

The maxLength attribute sets the maximum number of characters allowed in the search field.

Browser Support

maxLength Yes Yes Yes Yes Yes

Syntax

Return the maxLength property.

var v = searchObject.maxLength

Set the maxLength property.

searchObject.maxLength=number




Property Values

Value Description
number Set the maximum number of characters allowed in the search field.

Return Value

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

Example

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


<!DOCTYPE html>
<html>
<body>
<!--  w  w w  . j a  v  a 2 s . co  m-->
Search: <input type="search" id="mySearch">
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
    document.getElementById("mySearch").maxLength = "8";
}
</script>
</body>
</html>

The code above is rendered as follows:





Example 2

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


<!DOCTYPE html>
<html>
<body>
<!--from  www . j  a va2s  . com-->
Search: <input type="search" id="mySearch" maxlength="30">
<button onclick="myFunction()">test</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("mySearch").maxLength;
    document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>

The code above is rendered as follows: