You should not do this on keyup . Instead, try keypress . The problem is in keyup , the character is already running and written to the text field. Here is a good tutorial . Pay attention to the key press event.
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 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); }); });
source share