I know you want to avoid jQuery, but as the solution requires JavaScript, this solution (using jQuery 1.4) is the most consise and robust.
Inspired by, but an improvement over Dana Woodman's answer:
Changes from that answer are: Simplified and more generic, using jQuery.live and also not setting val if length is OK (leads to working arrow-keys in IE, and noticable speedup in IE):
// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').live('keyup blur', function() {
// Store the maxlength and value of the field.
var maxlength = $(this).attr('maxlength');
var val = $(this).val();
// Trim the field if it has content over the maxlength.
if (val.length > maxlength) {
$(this).val(val.slice(0, maxlength));
}
});
EDIT: Updated version for jQuery 1.7+, using on
instead of live
// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').on('keyup blur', function() {
// Store the maxlength and value of the field.
var maxlength = $(this).attr('maxlength');
var val = $(this).val();
// Trim the field if it has content over the maxlength.
if (val.length > maxlength) {
$(this).val(val.slice(0, maxlength));
}
});