Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 574
Calin-Andrei Burloiu Avatar asked Oct 06 '11 11:10

Calin-Andrei Burloiu


2 Answers

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.

like image 182
alex Avatar answered Sep 30 '22 14:09

alex


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

like image 27
Andy Avatar answered Sep 30 '22 14:09

Andy