Skip to content

Instantly share code, notes, and snippets.

@abitdodgy
Created November 27, 2012 16:37
Show Gist options
  • Save abitdodgy/4155330 to your computer and use it in GitHub Desktop.
Save abitdodgy/4155330 to your computer and use it in GitHub Desktop.
Lightweight jQuery character counter plugin.
(function ($) {
// Author: Mohamad El-Husseini, www.mohamad.im
// Light weight character counter for jQuery.
// Example: http://jsfiddle.net/yHPg7/6/
"use strict";
$.fn.counter = function (options) {
options = $.extend($.fn.counter.defaults, options);
function defaultText() {
return options.defaultText.replace(/minSize/ig, options.minSize);
}
function count(elem) {
var size = elem.val().length, target = elem.siblings(options.targetClass);
if (size === 0) {
target.html(defaultText());
} else if (size < options.minSize) {
target.html((options.minSize - size) + options.minWarning);
} else if (size >= options.minSize && size < options.warningSize) {
target.html('&nbsp;');
} else if (size >= options.warningSize && size < options.maxSize) {
target.html((options.maxSize - size) + options.maxWarning);
} else if (size >= options.maxSize) {
elem.val(elem.val().substring(0, options.maxSize));
target.html("0" + options.maxWarning);
}
}
this.each(function () {
var elem = $(this);
count(elem);
elem.keyup(function () {
count(elem);
});
elem.closest('form').submit(function () {
if (elem.val().length < options.minSize) {
$(this).find(options.targetClass).fadeOut('fast').fadeIn('fast').fadeOut('fast').fadeIn('fast');
return false;
}
});
return elem;
});
};
$.fn.counter.defaults = {
minSize: 15,
minWarning: " more to go...",
maxSize: 25,
maxWarning: " characters remaining...",
warningSize: 20,
targetClass: '.help-block',
defaultText: 'Enter at least minSize characters.'
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment