Created
February 9, 2011 18:14
-
-
Save alainravet/818933 to your computer and use it in GitHub Desktop.
limit the characters in a textarea + display 'n characters left'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $(document).ready(function() { | |
| $('textarea.word_count').each(function(){ | |
| var maxlimit = parseInt($(this).attr('maxlength')); | |
| // ...on page load | |
| var length = $(this).val().length; | |
| if(length >= maxlimit) { | |
| $(this).val($(this).val().substring(0, maxlimit)); | |
| length = maxlimit; | |
| } | |
| $(this).parent().find('.counter').html( (maxlimit - length) + ' characters left'); | |
| // on keyup events | |
| $(this).keyup(function(){ | |
| var new_length = $(this).val().length; | |
| if(new_length >= maxlimit) { | |
| $(this).val($(this).val().substring(0, maxlimit)); | |
| new_length = maxlimit; | |
| } | |
| var counterToUpdate = $(this).parent().find('.counter'); | |
| counterToUpdate.html( (maxlimit - new_length) + ' characters left'); | |
| }); | |
| }); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <p class="the_parent"> | |
| <text_area class="word_count" maxlength="140" ..> | |
| <span class="counter"></span> | |
| </p> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment