I am trying to get the text in a text box as the user types in it (jsfiddle playground):
The code runs without errors, except that the value of the input text
box, during onKeyPress
is always the value before the change:
Question: How do I get the text of a text box during
onKeyPress
?
There are three events related to "the user is typing" in the HTML DOM:
onKeyDown
onKeyPress
onKeyUp
In Windows, the order of WM_Key
messages becomes important when the user holds down a key, and the key begins to repeat:
WM_KEYDOWN('a')
- user has pushed down the A keyWM_CHAR('a')
- an a
character has been received from the userWM_CHAR('a')
- an a
character has been received from the userWM_CHAR('a')
- an a
character has been received from the userWM_CHAR('a')
- an a
character has been received from the userWM_CHAR('a')
- an a
character has been received from the userWM_KEYUP('a')
- the user has released the A keyWill result in five characters appearing in a text control: aaaaa
The important point being that the you respond to the WM_CHAR
message, the one that repeats. Otherwise you miss events when a key is pressed.
In HTML things are slightly different:
onKeyDown
onKeyPress
onKeyDown
onKeyPress
onKeyDown
onKeyPress
onKeyDown
onKeyPress
onKeyDown
onKeyPress
onKeyUp
Html delivers an KeyDown
and KeyPress
every key repeat. And the KeyUp
event is only raised when the user releases the key.
Take aways
onKeyDown
or onKeyPress
, but both are still raised before the input.value
has been updatedonKeyUp
, because it doesn't happen as the text in the text-box changes.Question: How do I get the text of a text-box during onKeyPress
?
Keep it simple. Use both onKeyPress()
and onKeyUp()
:
<input id="edValue" type="text" onKeyPress="edValueKeyPress()" onKeyUp="edValueKeyPress()">
This takes care of getting the most updated string value (after key up) and also updates if the user holds down a key.
jsfiddle: http://jsfiddle.net/VDd6C/8/