Posted By

Sverri on 07/29/10


Tagged

counter maxlength


Versions (?)

Visualize the "maxlength" attribute using a string length counter


 / Published in: jQuery
 

A little snippet that visualizes the \"maxlength\" attribute, used on the HTML \"input\" and \"textarea\" elements.\r\n\r\nThe snippet is set up in such a way as to give you easy control over...\r\n\r\n1. formatting of the counter\r\n2. the HTML tag where the counter is put\r\n3. where in the document you want the counter to be displayed\r\n\r\nThe snippet is quite self-explanatory, but I have commented on basically everything. Read the comments for further help.

  1. $(document).ready(function() {
  2.  
  3. // Targets all form elements that have the "maxlength" attribute and visualizes
  4. // the interaction with them by counting up to the maximum allowed characters.
  5. $("[maxlength]").each(function(){
  6.  
  7. // The format of the counter. {num} is the number that changes when the user
  8. // uses the keyboard, and {max} is the "maxlength" attribute. You can put
  9. // HTML tags into the formatting if you want.
  10. var format = '({num} out of {max})';
  11.  
  12. // The counter. Default is a <span> tag. You can do whatever you like with it,
  13. // such as add a class name, add CSS or even animate it. The formatted text
  14. // (fomat above) will be put into the tag itself.
  15. var counter = $('<span />').addClass("maxlengthdisplay");
  16.  
  17. // Set where the counter should be shown. You can place it wherever you like.
  18. // Default is right after the input or textarea.
  19. $(this).after( counter );
  20.  
  21. // Get the "maxlength" attribute and turn it into an integer (whole number).
  22. var max = parseInt($(this).attr("maxlength"),10);
  23.  
  24. // If "max" (ie. "maxlength") is less than 1 or not a number then abort.
  25. if (max<1 || typeof max!="number"){ counter.remove(); return; }
  26.  
  27. // Using the formatting we have set, prepare the counter.
  28. counter.html(format.replace("{num}",$(this).val().length).replace("{max}",max));
  29.  
  30. // Every time the user touches the keyboard...
  31. $(this).keyup(function(){
  32.  
  33. // ...count how many characters are in the input or textarea.
  34. var len = $(this).val().length;
  35.  
  36. // ...and update the counter accordingly.
  37. counter.html( format.replace("{num}",len).replace("{max}",max) );
  38. });
  39.  
  40. // That is it.
  41. });
  42.  
  43. });

Report this snippet  

You need to login to post a comment.