Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript, key press value is always one character behind the latest?

If I type 'St', by the time I press the t, if I output the input of textfield.value in the onkeypress/onkeydown functions, I only get 'S'.

Why is this? How do I get rid of this lag?

like image 606
Tom Avatar asked Aug 17 '10 13:08

Tom


People also ask

What is the difference between keypress and Keydown in Javascript?

The keydown event is fired when a key is pressed. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.

Is keypress deprecated?

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.


2 Answers

use the keyup event instead of keypress. keydown will show the before-keystroke value, as will keypress (apparently).

like image 117
lincolnk Avatar answered Oct 12 '22 19:10

lincolnk


Within the keypress event, it's still possible to prevent the typed character from registering, so the input's value canot be updated until after the keypress event. You can use the keyup event instead, or use window.setTimeout() to set up a delay.

like image 42
Tim Down Avatar answered Oct 12 '22 19:10

Tim Down