An HTML text input has an attribute called \"maxlength\", implemented by browsers, which if set blocks user input after a certain number of characters.
An HTML texta
I figure I can give this a go, just another way of doing the same thing. I like this way of doing it because you could wrap this in some code to check if you're running in IE since maxlength does work on text areas in webkit and gecko browsers. It depends on the maxlength property being set on the textarea element in the html. Also because it actually works as the maxlength property works in the browser by default, preventing the user from adding more than the specified characters.
$(document).ready(function () {
$('textarea').on('keyup', function () {
// Store the maxlength and value of the field.
if (!maxlength) {
var maxlength = $(this).attr('maxlength');
}
var val = $(this).val();
var vallength = val.length;
// alert
if (vallength >= maxlength) {
alert('Please limit your response to ' + maxlength + ' characters');
$(this).blur();
}
// Trim the field if it has content over the maxlength.
if (vallength > maxlength) {
$(this).val(val.slice(0, maxlength));
}
});
//remove maxlength on blur so that we can reset it later.
$('textarea').on('blur', function () {
delete maxlength;
});
});