Chaka Chaka - 15 days ago 8
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.

Jquery:

$(document).ready( function () {

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

$("textarea").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").val($("textarea").val().slice(0, maxLength));
$(remainingLengthTempId).text(0);

}
}


Html:

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

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

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

Answer

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

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

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