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.......
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.......
On
Change to the keyup event and it works fine for me here: http://jsfiddle.net/jfriend00/grZW7/. The keypress event only happens on some keys and may happen BEFORE the text of the field is updated whereas keyup always happens afterwards.
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/