charCount.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. cssWarning: 'warning',
  24. cssExceeded: 'exceeded',
  25. counterText: ''
  26. };
  27. var options = $.extend(defaults, options);
  28. function calculate(obj){
  29. var count = $(obj).val().length;
  30. var available = options.allowed - count;
  31. if(available <= options.warning && available >= 0){
  32. $(obj).next().addClass(options.cssWarning);
  33. } else {
  34. $(obj).next().removeClass(options.cssWarning);
  35. }
  36. if(available < 0){
  37. $(obj).next().addClass(options.cssExceeded);
  38. } else {
  39. $(obj).next().removeClass(options.cssExceeded);
  40. }
  41. $(obj).next().html(options.counterText+'<b>' + available+'</b>个字(不含客户昵称和签名)');
  42. };
  43. this.each(function() {
  44. $(this).after('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>');
  45. calculate(this);
  46. $(this).keyup(function(){calculate(this)});
  47. $(this).change(function(){calculate(this)});
  48. });
  49. };
  50. })(jQuery);