Skip to content

Instantly share code, notes, and snippets.

@afahy
Created October 22, 2009 21:03
Show Gist options
  • Save afahy/216332 to your computer and use it in GitHub Desktop.
Save afahy/216332 to your computer and use it in GitHub Desktop.
Maxlength on textarea
// Triggers "updated.maxlength" event when updated (post-keyup)
// evt sends: { maxlength: Number, remaining: Number }
(function($){
var f = function(num){
return this.each(function(){
var $this = $(this),
chars = num || $this.attr("data-maxlength") || f.num,
remaining = function(){ return chars - $this.val().length };
if(this.nodeName.toLowerCase() == "textarea"){
$this.bind("keyup.maxlength", function(){
var val = $this.val();
val.length > chars && $this.val(val.substr(0,chars))
$this.trigger("updated.maxlength",{ maxlength: chars, remaining: remaining() });
});
}
});
}
f.num = 100;
$.extend($.fn, { maxlength: f });
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment