Skip to content

Instantly share code, notes, and snippets.

@evadi
Created March 22, 2013 23:58
Show Gist options
  • Save evadi/5225675 to your computer and use it in GitHub Desktop.
Save evadi/5225675 to your computer and use it in GitHub Desktop.
jQuery plugin for character limits in text areas
(function ($) {
$.fn.characterLimit = function (options) {
var settings = $.extend({
'maxCharacters': 100
}, options);
return this.each(function () {
var $this = $(this);
$this.keypress(function (e) {
var char = String.fromCharCode(e.which);
var curVal = $(this).val();
var forecastVal = curVal + char;
//when the character limit is about to be exceeded preventDefault
//halts the new character being assigned to the text area
if (forecastVal.length >= settings.maxCharacters) {
e.preventDefault();
}
});
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment