Set maxlength in Html Textarea

Hitesh Prajapati picture Hitesh Prajapati · Dec 16, 2010 · Viewed 110.6k times · Source

How can I set the maxlength in a textarea? And why maxlength is not working properly in textarea?

Answer

aqingsao picture aqingsao · Aug 26, 2012

Before HTML5, we have an easy but workable way: Firstly set an maxlength attribute in the textarea element:

<textarea maxlength='250' name=''></textarea>  

Then use JavaScript to limit user input:

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

Make sure the bind both "input" and "propertychange" events to make it work on various browsers such as Firefox/Safari and IE.