The HTML maxlength attribute can be used to specify the maximum number of characters allowed in an element.
Example: Form <input>
field with maxlength of 10 and 20 characters
1 2 3 4 5 6 7 |
<form> <label for="username">Username</label> <input type="text" name="username" maxlength="10"><br><br> <label for="email">Email</label> <input type="email" name="email" maxlength="20"><br><br> <input type="submit" name="submit"> </form> |
Output
It works and applicable to <input>
types(that takes string value) and <textarea>
elements of HTML.
Syntax
For <input>
element:-
For <textarea>
element:-
Parameter description
Attribute Value | Description |
---|---|
number | It is the maximum number of characters allowed in an element. Its default value is 524288. |
Input Field with HTML Maxlength Attribute
The maxlength attribute can be used in <input>
elements that accept string type value. The input types like text, email, number, and password are applicable for this attribute.
Example: Form <input>
field with maxlength 10
1 2 3 4 5 |
<form> <label for="username">Username</label> <input type="text" name="username" maxlength="10"><br><br> <input type="button" name="submit"> </form> |
Output
The above example accepts maximum of 10 string content from the users who want to fill the form.
Textarea with Maxlength Attribute
The maxlength attribute in HTML is also useful when you want to limit the <textarea>
field content length. By making it required, you can define how many digits users can fill in the textarea.
Example: Form <textarea>
field with maxlength of 40 characters
1 2 3 4 5 6 7 |
<form> <label for="name">Name</label> <input type="text" name="name" maxlength="10"><br><br> <label for="Message">Message</label> <textarea name="message" rows="3" col="8" maxlength="40"></textarea><br><br> <input type="button" name="submit"> </form> |
Output
Browser Compatibility
The maxlength
attribute in HTML supports all the major browsers as given below:-
- Google Chrome
- Internet Explorer
- Firefox
- Safari
- Opera Mini
Read More