Calin-Andrei Burloiu
Calin-Andrei Burloiu

Reputation: 1481

Show in real time the number of characters in a HTML textarea while the user types

I am trying to create a blog comment form with a textarea and a span which shows to the user the number of remaining characters that can be introduced in 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 when typing .keydown is called first, which prints the number of remaining characters and then the new character typed is shown in the textarea. So the number of remaining characters does not have a correct value, being bigger by one unit. To make this work .keydown should be called after the insertion of the new character.

How can I resolve this problem?

Upvotes: 5

Views: 2508

Answers (5)

Guffa
Guffa

Reputation: 700262

Use the keypress event instead, which happens when a key produces a character, not when the key is pressed. (For example the shift key causes a keydown event but not a keypress event, and a key that repeats causes keypress events for each character, but only a keydown event at the first one.)

Use the setTimeout method to start a timer that will run the code after the event has been handled:

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

Upvotes: 0

Thijs
Thijs

Reputation: 3055

try the .keyup event instead

Upvotes: 0

alex
alex

Reputation: 490183

Use keyup() instead.

You will also want to bind a few other events.

Use bind('keyup paste drop').

keyup for event when key is released, paste if someone pastes text in your textarea, and drop if someone drops a chunk of text in your textarea.

jsFiddle.

Upvotes: 5

Andy
Andy

Reputation: 30135

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

Upvotes: 1

Alex
Alex

Reputation: 9031

Why not use .keyup() ?

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

Upvotes: 0

Related Questions