Chaka Chaka - 9 months ago 64
jQuery Question

Jquery help to enforce maxlength on textarea?

Here is Jquery to enforce maxlength for textarea when you add the attribute "maxlength". Maxlength is not supported with IE. How do I adjust my code to handle multiple textarea(s) on the page? Currently
if I add text to any textarea, they all countdown with the same value.


$(document).ready( function () {

maxLength = $("textarea").attr("maxlength");
$("textarea").after("<div><span id='remainingLengthTempId'>"
+ maxLength + "</span> remaining</div>");

$("textarea").bind("keyup change", function(){checkMaxLength(, 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").val($("textarea").val().slice(0, maxLength));



<textarea id="1" maxlength="200" rows="10" cols="60" ></textarea>

<textarea id="2" maxlength="200" rows="10" cols="60" ></textarea>

<textarea id="3" maxlength="100" rows="10" cols="60" ></textarea>

Answer Source

This is the best solution! Put this into your script tag in HTML code

    $(function() {  
        $("textarea[maxlength]").bind('input propertychange', function() {  
            var maxLength = $(this).attr('maxlength');  
            if ($(this).val().length > maxLength) {  
                $(this).val($(this).val().substring(0, maxLength));  

and now use < textarea maxlength="{your limit}" > for {your limit} chars limit.