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

3 comments on “Add maxlength on textArea using jQuery

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

    Reply
  2. 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 ?

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *