How can I set the maxlength
in a textarea
? And why maxlength
is not working properly in textarea
?
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.