Posted By

housecor on 09/15/10


Tagged

javascript jquery textarea maxlength


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Priestd09


Enforce maxlength for all textareas on page


 / Published in: JavaScript
 

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.

  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  

You need to login to post a comment.