Show in real time the number of characters in the HTML text box while the user enters

I am trying to create a comment on a form blog with textarea and span that shows the user the number of remaining characters that can be entered into the text area.

So, I have this form:

 <form action="comment.php" method="POST" accept-charset="utf-8"> <textarea name="comment" id="comment" rows="4" cols="56"></textarea> <input type="submit" value="Post" /> <span id="comment-chars-left">512</span> characters left </form> 

And then I wrote the following jQuery code:

 $('#comment') .keydown(function(event) { $('#comment-chars-left').html('' + (512 - $textarea.val().length)); }); 

The problem is that the first time .keydown call .keydown , the number of remaining characters is called, and then the new character is entered into textarea . Thus, the number of remaining characters does not have the correct value, being one more. To make this work .keydown must be called after inserting a new character.

How can I solve this problem?

+4
source share
5 answers

Use keyup() instead.

You will also want to associate several other events.

Use bind('keyup paste drop') .

keyup for the event when the key is released, paste if someone inserts text into textarea and drop if someone throws a piece of text into textarea .

jsFiddle .

+4
source

you can use $('#comment').keyup() :)

+1
source

Why not use .keyup() ?

 $('#comment') .keyup(function(event) { $('#comment-chars-left').html('' + (512 - $textarea.val().length)); }); 
0
source

try the .keyup event

0
source

Instead, use the keypress event, which occurs when a key creates a character, and not when a key is pressed. (For example, the shift key keydown event, but not a keypress event, but a repeating key keypress events for each character, but only the keydown event on the first.)

Use the setTimeout to start a timer that will run the code after processing the event:

 $('#comment') .keypress(function() { window.setTimeout(function(){ $('#comment-chars-left').html('' + (512 - $textarea.val().length)); }, 0); }); 
0
source

All Articles