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?
Use
keyup()instead.You will also want to bind a few other events.
Use
bind('keyup paste drop').keyupfor event when key is released,pasteif someone pastes text in yourtextarea, anddropif someone drops a chunk of text in yourtextarea.jsFiddle.