Created
March 24, 2012 21:04
-
-
Save lu1s/2187780 to your computer and use it in GitHub Desktop.
jQuery Character Count Plugin with preventExceeding extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Character Count Plugin - jQuery plugin | |
* Dynamic character count for text areas and input fields | |
* written by Alen Grakalic | |
* http://cssglobe.com/post/7161/jquery-plugin-simplest-twitterlike-dynamic-character-count-for-textareas | |
* | |
* Copyright (c) 2009 Alen Grakalic (http://cssglobe.com) | |
* Dual licensed under the MIT (MIT-LICENSE.txt) | |
* and GPL (GPL-LICENSE.txt) licenses. | |
* | |
* Built for jQuery library | |
* http://jquery.com | |
* | |
* Added the preventExceeding {true, false} option. When set to true, it prevents the user | |
* from adding (pasting or typing) more text than the allowed. - Luis (twitter.com/pulidoman) | |
* | |
*/ | |
(function($) { | |
$.fn.charCount = function(options){ | |
// default configuration properties | |
var defaults = { | |
allowed: 140, | |
warning: 25, | |
css: 'counter', | |
counterElement: 'span', | |
cssWarning: 'warning', | |
cssExceeded: 'exceeded', | |
counterText: '', | |
preventExceeding: false // added | |
}; | |
var options = $.extend(defaults, options); | |
function calculate(obj){ | |
var count = $(obj).val().length; | |
var available = options.allowed - count; | |
if(available <= options.warning && available >= 0){ | |
$(obj).next().addClass(options.cssWarning); | |
} else { | |
$(obj).next().removeClass(options.cssWarning); | |
} | |
if(available < 0){ | |
$(obj).next().addClass(options.cssExceeded); | |
if(options.preventExceeding){ // added | |
var newstring = $(obj).val(); // added | |
var diff = options.allowed - newstring.length; // added | |
newstring = newstring.slice(0,diff); // added | |
$(obj).val(newstring); // added | |
calculate(this); // added | |
} // added | |
} else { | |
$(obj).next().removeClass(options.cssExceeded); | |
} | |
$(obj).next().html(options.counterText + available); | |
}; | |
this.each(function() { | |
$(this).after('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>'); | |
calculate(this); | |
$(this).keyup(function(){calculate(this)}); | |
$(this).change(function(){calculate(this)}); | |
}); | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment