Skip to content

Instantly share code, notes, and snippets.

@wrboyce
Created June 26, 2009 09:32
Show Gist options
  • Save wrboyce/136388 to your computer and use it in GitHub Desktop.
Save wrboyce/136388 to your computer and use it in GitHub Desktop.
(function($) {
$.fn.maxlength = function(options) {
var settings = $.extend({
maxWords: 60,
badClass: false, // apply this class to an invalid element
statusIdSuffix: '_wc', // hold the words remaining information (elementId_wc)
errorMsg: 'To many words have been entered in this field.',
}, options);
return this.each(function() {
var el = $(this);
if (!el.is('textarea'))
return false;
el.keypress(function(e) {
var wc = el.val().split(/[\s\.\?]+/).length;
if (settings.statusIdSuffix) {
statusEl = $('#' + this.id + settings.statusIdSuffix);
if (statusEl.length)
statusEl.text(wc + '/' + settings.maxWords);
}
if (wc >= settings.maxWords) {
$(el[0].form).find('input[type=submit]').attr('disabled', 'disabled');
statusEl.text(statusEl.text() + ' ' + settings.errorMsg);
if (settings.badClass)
el.addClass(settings.badClass);
} else {
$(el[0].form).find('input[type=submit]').attr('disabled', '');
el.removeClass(settings.badClass);
}
});
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment