jquery.charCount.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Character Count Plugin - jQuery plugin
  3. * Dynamic character count for text areas and input fields
  4. * written by Alen Grakalic
  5. * http://cssglobe.com/post/7161/jquery-plugin-simplest-twitterlike-dynamic-character-count-for-textareas
  6. *
  7. * Copyright (c) 2009 Alen Grakalic (http://cssglobe.com)
  8. * Dual licensed under the MIT (MIT-LICENSE.txt)
  9. * and GPL (GPL-LICENSE.txt) licenses.
  10. *
  11. * Built for jQuery library
  12. * http://jquery.com
  13. *
  14. */
  15. (function($) {
  16. $.fn.charCount = function(options){
  17. // default configuration properties
  18. var defaults = {
  19. allowed: 140,
  20. warning: 25,
  21. css: 'counter',
  22. counterElement: 'span',
  23. counterContainerID:'',
  24. cssWarning: 'warning',
  25. cssExceeded: 'exceeded',
  26. firstCounterText: '',
  27. endCounterText: '',
  28. errorCounterText: '',
  29. errortype: 'positive' // positive or negative
  30. };
  31. var options = $.extend(defaults, options);
  32. function calculate(obj){
  33. var count = $(obj).val().length;
  34. var counterText = options.firstCounterText;
  35. var _css = '';
  36. containerObj = $("#"+options.counterContainerID);
  37. var available = options.allowed - count;
  38. if(available <= options.warning && available >= 0){
  39. _css = options.cssWarning;
  40. }
  41. if(available < 0){
  42. if (options.errortype == 'positive')available = -available;
  43. counterText = options.errorCounterText;
  44. _css = options.cssExceeded;
  45. } else {
  46. counterText = options.firstCounterText;
  47. }
  48. $(containerObj).children().html(counterText +'<em class="'+ _css +'">'+ available +'</em>'+ options.endCounterText);
  49. };
  50. this.each(function() {
  51. $("#"+options.counterContainerID).append('<'+ options.counterElement +' class="' + options.css + '"></'+ options.counterElement +'>');
  52. calculate(this);
  53. $(this).keyup(function(){calculate(this)});
  54. $(this).change(function(){calculate(this)});
  55. $(this).focus(function(){calculate(this)});
  56. });
  57. };
  58. })(jQuery);