Main Tutorials

Add maxlength on textArea using jQuery

The “maxlength” attribute is not supported in textArea, but you can use JavaScript to limit the length of textArea dynamically.

HTML 5
The textArea “maxlength” attribute is supported in HTML 5, the problem is not all browsers support HTML 5, especially, the old IE.

jQuery Example

A jQuery example to implement the “maxlength” effect on a textarea field.


<html>
<head>
<script language="javascript" type="text/javascript" 
	src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script language="javascript" type="text/javascript">

    $(document).ready( function () {

	maxLength = $("textarea#comment").attr("maxlength");
        $("textarea#comment").after("<div><span id='remainingLengthTempId'>" 
                  + maxLength + "</span> remaining</div>");
		
        $("textarea#comment").bind("keyup change", function(){checkMaxLength(this.id,  maxLength); } )

    });

    function checkMaxLength(textareaID, maxLength){
	
        currentLengthInTextarea = $("#"+textareaID).val().length;
        $(remainingLengthTempId).text(parseInt(maxLength) - parseInt(currentLengthInTextarea));
        
		if (currentLengthInTextarea > (maxLength)) { 
			
			// Trim the field current length over the maxlength.
			$("textarea#comment").val($("textarea#comment").val().slice(0, maxLength));
			$(remainingLengthTempId).text(0);
			
		}
    }
</script>
</head>

<body>
<h1>TextArea maxlength with jQuery</h1>
<textarea id="comment" maxlength="10" rows="10" cols="60" ></textarea>
</body>
</html>

Demo

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Sergio Casais
3 years ago

Excelent, thank you very very very much!!
@SergioCasais

Ashwin
5 years ago

Thanks for your solution, but if we open this page on an Android device using chrome browser the mbile keyboard allows the user to type even if max character limit even thought it does not display to the user, do you know how to avoid that ?

JR
11 years ago

Your code still allow keydown/keypress after max chars?