HTML DOM Input Search maxLength Property

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


Following is the syntax for −

Set the maxLength property −

passwordObject.maxLength = integer

Here, integer specifies the maximum number of characters that can be entered in the search field. The default value for this is 524288.


Let us look at an example for the maxLength property −

<!DOCTYPE html>
<h1>Input Search maxLength Property</h1>
FRUITS: <input type="search" id="SEARCH1" name="fruits" maxlength="5">
<p>Increase the maximum number of characters to be entered for the above search field by clicking below button</p>
<button onclick="changeMax()">CHANGE LENGTH</button>
<p id="Sample"></p>
   function changeMax() {
      document.getElementById("SEARCH1").maxLength = "15";
      document.getElementById("Sample").innerHTML = "Maximum number of characters are increased to 15";


This will produce the following output −

On clicking the CHANGE LENGTH −

In the above example −

We have first created an <input> element with type=”search”, id=”SEARCH1”, name=”fruits” and its maxlength attribute set to 5. The maxlength attribute specifies that there can only be 5 characters in the given search field. The search field is inside a form −

<form> FRUITS: <input type="search" id="SEARCH1" name="fruits" maxlength="5"> </form>

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

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

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

function changeMax() {
   document.getElementById("SEARCH1").maxLength = "15";
   document.getElementById("Sample").innerHTML = "Maximum number of characters are now increased to 15";

Updated on: 19-Aug-2019


Kickstart Your Career

Get certified by completing the course

Get Started