Add maxlength to textarea with jQuery

An html input field has a maxlength attribute to limit the number of characters that can be entered in the field, but an html textarea does not.  However, maxlength functionality can be easily added to textarea controls with a little bit of jQuery.

This snippet looks for textareas that have a maxlength attribute, and limits the number of characters to the number in the attribute.  This could use a bit of validation code, perhaps – making sure that the maxlength value is numeric, for example.  But you get the idea…

$(document).ready(function(){

    $(‘textarea[maxlength]’).keyup(function() {

        //get textarea text and maxlength attribute value
        var t = $(this);
        var text = t.val();
        var limit = t.attr(‘maxlength’);

        //if textarea text is greater than maxlength limit, truncate and re-set text
        if (text.length > limit) {
            text = text.substring(0, limit);
            t.val(text);
        }
    });

});

Advertisements