Limiting the number of text in textarea using JQuery

Posted by Tim on May 20, 2009 in Open Source |

example: <textarea id=”id” maxlength=”255″></textarea>

jQuery(‘textarea[maxlength]‘).keyup(function() {
var max = parseInt(jQuery(this).attr(‘maxlength’));
if (jQuery(this).val().length > max) {
jQuery(this).val(jQuery(this).val().substr(0, jQuery(this).attr(‘maxlength’)));
}
if (jQuery(this).parent().find(‘.charsRemaining’).length > 0) jQuery(this).parent().find(‘.charsRemaining’).html(‘You have ‘ + (max – jQuery(this).val().length) + ‘ characters remaining’);
else jQuery(this).parent().append(‘<div class=”charsRemaining”>You have ‘ + (max – jQuery(this).val().length) + ‘ characters remaining</div>’);

});

Tags:

2 Comments

  • Byron says:

    What if the user enters text via a way other than the keyboard? I think the best way to deal with this is by using timers, though that can get messy if your not careful…

  • Tim says:

    Good point..It was a decision based on time and the type of market we are providing our software for.

Leave a Reply

Copyright © 2008-2012 Codelab Blog All rights reserved.
Desk Mess Mirrored version 1.9.1 theme from BuyNowShop.com.