I’ve gone over the code several times and can’t figure out why the first keystroke doesn’t seem to count.
When the textarea is an empty string, the counter display should read accurately. But it seems that the textarea needs to be empty twice…….
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Try listening to the
keyupevent instead.The
keypressevent is fired when the actual character is being inserted in the textarea. When you read the value of the textarea —message.get('value'), the old value before thekeypressevent is returned. This explains why the counter shows an outdated (inaccurate) number of characters left.More about
keydown,keypress, andkeyupevents: http://www.quirksmode.org/dom/events/keys.htmlUPDATE:
There is a better way to detect changes to
<input>and<textarea>.The YUI
event-valuechangemodule provides avaluechangeevent that fires when the user changes the input value by:Here’s how to use it on an input with ID
message:Live demo: http://jsfiddle.net/Pd9X9/