Enforce maxlength for all textareas on page


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

Just be sure to slap the div for the chars left message within the same div/p as the textarea so the dom walk works.


Copy this code and paste it in your HTML
  1. $('textarea').keyup(function () {
  2. var max = 4000;
  3. if ($(this).val().length > max) {
  4. $(this).val($(this).val().substr(0, max));
  5. }
  6.  
  7. $(this).parent().find('.chars_remaining').html('You have ' + (max - $(this).val().length) + ' characters remaining').show();
  8. });
  9.  
  10. //hide chars remaining count on blur
  11. $('textarea').blur(function () { $('.chars_remaining').fadeOut('fast'); });
  12.  
  13. //and in the front end:
  14. <span class="chars_remaining ui-state-highlight"></span>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.