views:

1422

answers:

4

So my site has an input box, which has a onkeydown event that merely alerts the value of the input box.

Unfortunately the value of the input does not include the changes due to the key being pressed.

For example for this input box:

<input onkeydown="alert(this.value)" type="text" value="cow" />

The default value is "cow". When you press the key "s" in the input, you get an alert("cow") instead of an alert("cows"). How can I make it alert("cows") without using onkeyup? I don't want to use onkeyup because it feels less responsive.

One partial solution is to detect the key pressed and then append it to the input's value, but this doesn't work in all cases such as if you have the text in the input highlighted and then you press a key.

Anyone have a complete solution to this problem?

Thanks

A: 

keyup/down events are handled differently in different browsers. The simple solution is to use a library like mootools, which will make them behave the same, deal with propagation and bubbling, and give you a standard "this" in the callback.

Jeff Ober
+3  A: 

You can do this:

<input onkeypress="alert(this.value + String.fromCharCode(event.which))"
    type="text" value="cow" />

which works in everything except IE, which uses event.keyCode instead of event.which.

Note I'm using onkeypress instead of onkeydown, as onkeypress gives proper capitalisation.


edit: Previous solution only works in one very contrived case. Try this:

<input id="e"
    onkeydown="window.setTimeout( function(){ alert(e.value) }, 1)"
    type="text" value="cow" />

This sets a 1ms timeout that should happen after the keypress and keydown handlers have let the control change its value. If your monitor is refreshing at 60fps then you've got 16ms of wiggle room before it lags 2 frames.

kibibu
thanks for the solution, but unfortunately this doesn't work in the case where the input is highlighted, and then a key is pressed. so for example if "cow" is highlighted and you press "s", it alerts "cows" when it should alert "s"
inktri
Yeah, i didn't read the original question well enough!
kibibu
Updated to include a version that does work, at least in my browser.
kibibu
A: 

To my knowledge you can't do that with a standard input control unless you roll your own.

Sir Psycho
A: 

Thank you for setTimeout example!

Boris Turk