/src/main/webapp/public/js/lib/jquery.limit.js

http://thoughtsite.googlecode.com/ · JavaScript · 45 lines · 32 code · 6 blank · 7 comment · 14 complexity · 181e91088fd5f4fd7fe408bb57fcbb4d MD5 · raw file

  1. (function($) {
  2. $.fn
  3. .extend( {
  4. limit : function(limit, element) {
  5. var interval, f;
  6. var self = $(this);
  7. $(this)
  8. .keypress(function(event) {
  9. // get element
  10. var val = $(self).val();
  11. // Get the code of key pressed
  12. var keyCode = event.keyCode;
  13. // Check if it has a selected text
  14. var hasSelection = document.selection ? document.selection
  15. .createRange().text.length > 0
  16. : this.selectionStart != this.selectionEnd;
  17. // return false if can't write more
  18. if ((val.length >= limit
  19. && (keyCode > 50 || keyCode == 32
  20. || keyCode == 0 || keyCode == 13)
  21. && !event.ctrlKey && !event.altKey && !hasSelection)) {
  22. return false;
  23. }
  24. });
  25. $(this).keyup(function(event) {
  26. // If the keypress fail and allow write more text that
  27. // required, this event will remove it
  28. substring();
  29. });
  30. substringFunction = "function substring(){ var val = $(self).val();var length = val.length;if(length > limit){$(self).val($(self).val().substring(0,limit));}";
  31. if (typeof element != 'undefined')
  32. substringFunction += "if($(element).html() != limit-length){$(element).html((limit-length<=0)?'0':limit-length);}"
  33. substringFunction += "}";
  34. eval(substringFunction);
  35. // run first time when it loads
  36. substring();
  37. }
  38. });
  39. })(jQuery);