The keyup
event fires after the default behaviour (populating text area) has occurred.
It’s better to use the keypress
event, and filter non-printable characters.
Demo: http://jsfiddle.net/3uhNP/1/ (with max length 4)
jQuery(document).ready(function($) {
var max = 400;
$('textarea.max').keypress(function(e) {
if (e.which < 0x20) {
// e.which < 0x20, then it's not a printable character
// e.which === 0 - Not a character
return; // Do nothing
}
if (this.value.length == max) {
e.preventDefault();
} else if (this.value.length > max) {
// Maximum exceeded
this.value = this.value.substring(0, max);
}
});
}); //end if ready(fn)