Skip to content

Instantly share code, notes, and snippets.

@dewyze
Last active September 15, 2016 08:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dewyze/4521686 to your computer and use it in GitHub Desktop.
Save dewyze/4521686 to your computer and use it in GitHub Desktop.
jQuery textarea maxlength for both keypress and paste. Covers lack of "maxlength" attribute in IE. Some credit goes to here: http://stackoverflow.com/questions/6877518/jquery-textarea-maxlength for the keypress section.
var ignore = [8,9,13,33,34,35,36,37,38,39,40,46];
$('textarea[maxlength]')
.live({
keypress: 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 );
}
},
paste: function() {
var self = $(this),
maxlength = self.attr('maxlength');
setTimeout(function () {
self.val(self.val().substr(0,maxlength));
}, 100)
}
});
@jpsirois
Copy link

jpsirois commented Feb 7, 2013

I’ve updated it to be more future proof here: https://gist.github.com/jpsirois/4731345

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment