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')
.
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.
you could use $('#comment').keyup()
:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With