YUI maximum length for textarea (with counter)


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. //++++++++++++++++++++++++++++++++++++
  2. // YUI textarea
  3. // 4-12-2008 - Edwart Visser
  4. // maximum amount of character in textarea
  5. //
  6. // HOW TO USE:
  7. // write textarea as follows <textarea class="max" rel="20"></textarea>
  8. // class "max" is needed
  9. // rel defines the maximum amount of characters
  10. //
  11. // REQUIRES: yahoo-dom-event.js
  12. //++++++++++++++++++++++++++++++++++++
  13. var Dom = YAHOO.util.Dom;
  14. var Event = YAHOO.util.Event;
  15.  
  16. YAHOO.namespace("lutsr");
  17.  
  18. YAHOO.lutsr.maxTextarea = {
  19. init : function() {
  20. // get all textarea's and extend them
  21. var textareaEls = Dom.getElementsByClassName("max");
  22. if(textareaEls.length > 0) {
  23. for(var i=0; i < textareaEls.length; i++) {
  24. this.extend(textareaEls[i]);
  25. }
  26. }
  27. },
  28. extend : function(el) {
  29. el.maxChars = el.getAttribute("rel");
  30. // add display of amount of characters in textarea
  31. var statusDisplay = document.createElement("div");
  32. statusDisplay.className = "display";
  33. el.statusDisplayEl = statusDisplay;
  34.  
  35. // set status text
  36. var statusText = "You have " + el.maxChars + " left for your message.";
  37. statusDisplay.innerHTML = statusText;
  38. el.parentNode.insertBefore(statusDisplay,el);
  39.  
  40. // add onchange event
  41. Event.addListener(el,"keyup",this.changeStatusMessage,el);
  42. },
  43. changeStatusMessage : function(e,el) {
  44. var curLength = el.value.length;
  45. var leftLength = el.maxChars - curLength;
  46. if(leftLength > 0) {
  47. // no problem
  48. if(Dom.hasClass(el.statusDisplayEl,"error")){
  49. Dom.removeClass(el.statusDisplayEl,"error")
  50. }
  51. var statusText = "You have " + leftLength + " left for your message.";
  52. el.statusDisplayEl.innerHTML = statusText;
  53. } else {
  54. // string length too long
  55. if(!Dom.hasClass(el.statusDisplayEl,"error")){
  56. Dom.addClass(el.statusDisplayEl,"error")
  57. }
  58. var statusText = "You're message has too many characters.";
  59. el.statusDisplayEl.innerHTML = statusText;
  60. }
  61. }
  62. }
  63.  
  64. initPage = function() {
  65. YAHOO.lutsr.maxTextarea.init();
  66. }
  67.  
  68. Event.on(window,"load",initPage);

URL: http://www.lutsr.nl/yui/textarea/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.