Skip to content

Instantly share code, notes, and snippets.

@sanand0
Created September 7, 2010 07:17
Show Gist options
  • Save sanand0/567987 to your computer and use it in GitHub Desktop.
Save sanand0/567987 to your computer and use it in GitHub Desktop.
Restricts number of characters to maxlength in textarea
// Textarea maxlength
// Ensures that textarea's maxlength is validated
//
// (c) S Anand, 2010, MIT License
// Credits: http://yelotofu.com/2009/12/jquery-textarea-max-length/
// Credits: http://stackoverflow.com/questions/43569/max-length-for-html-text-areas
(function() {
var ignore = [8,9,13,33,34,35,36,37,38,39,40,46];
function limit(event) {
var self = $(this),
maxlength = self.attr('maxlength'),
len = self.val().length;
if (maxlength && maxlength > 0 && len > maxlength) {
self.val(self.val().substr(0, maxlength));
}
}
jQuery(function($) {
$('textarea[maxlength]').live('keypress', function(event) {
var self = $(this),
maxlength = self.attr('maxlength'),
code = $.data(this, 'keycode');
if (maxlength && maxlength > 0) {
return ( self.val().length < maxlength
|| $.inArray(code, ignore) !== -1 );
}
})
.live('keydown', function(event) {
$.data(this, 'keycode', event.keyCode || event.which);
})
.live('keyup', limit)
.live('change', limit)
.bind('paste', function(e) { // Do not allow pasting anything over the length
var self = $(this),
maxlength = self.attr('maxlength');
if (window.clipboardData && $(this).val().length + window.clipboardData.getData("Text").length > maxlength) {
return false;
}
return true;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment