Last active
September 15, 2016 08:53
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I’ve updated it to be more future proof here: https://gist.github.com/jpsirois/4731345