jQuery: Textarea maxlength
Being able to restrict the maximum length of user input from the interface directly is very convenient and practical in use. We do this a lot with input elements. Unfortunately textarea elements do not natively support the maxlength attribute. This attribute was finally added in HTML5 but at the time of writing Chrome is the only browser supporting it.
Naturally many have used JavaScript to rectify this problem and I'd be doing the same here. The difference is we won't be putting anything special in the markup but will simply use the maxlength attribute within our textarea as if it's native — like so:
HTML
<textarea cols="30" rows="5" maxlength="10"></textarea>
This is looking good for HTML5 compatibility. And here's the magic:
jQuery
jQuery(function($) { // ignore these keys var ignore = [8,9,13,33,34,35,36,37,38,39,40,46]; // use keypress instead of keydown as that's the only // place keystrokes could be canceled in Opera var eventName = 'keypress'; // handle textareas with maxlength attribute $('textarea[maxlength]') // this is where the magic happens .live(eventName, function(event) { var self = $(this), maxlength = self.attr('maxlength'), code = $.data(this, 'keycode'); // check if maxlength has a value. // The value must be greater than 0 if (maxlength && maxlength > 0) { // continue with this keystroke if maxlength // not reached or one of the ignored keys were pressed. return ( self.val().length < maxlength || $.inArray(code, ignore) !== -1 ); } }) // store keyCode from keydown event for later use .live('keydown', function(event) { $.data(this, 'keycode', event.keyCode || event.which); }); });
See live example.
This code could probably be enhanced further by triggering custom events when the maximum length is reached or include a character counter of some sort within the keypress handler. Your imagination is the limit!


By Tontyna at 31 Dec 2009 8:20 am PST
By caphun at 3 Jan 2010 12:35 pm PST
By Huzoor Bux at 6 Jan 2010 6:28 pm PST
By roren at 12 Jan 2010 12:23 pm PST
By XAOdry at 22 Jan 2010 7:29 am PST