How do I obtain the value of a textbox after an OnKeyPress event? For example, Let’s say I have the following code:
<input type = "number" id = "foo" onKeyPress = "submit();"/>
<script type = "text/javascript">
function submit()
{
var textValue = document.getElementById("foo").value;
alert(textValue);
}
</script>
Unfortunately, this doesn’t work because after the OnKeyPress is triggered, the variable textValue will still be one character behind. I would use OnKeyUp, but sadly it doesn’t work on Android devices unless the <input type = "text"> which doesn’t work in my situation… Does anyone know a way to do this?
If the only problem is Android devices, I suggest using onkeyup for everyone else. Then you can detect if it’s android (or if keyup is supported on the input) and, if necessary, implement an Android specific solution.
You can then remove the
onKeyPress = "submit();"from your input.When not on Android, this code will act normally, using the keyup event. When the client is on Android, it will wait for 1/100th of a second, enough time for the input to update, but too short to be noticeable.
Normally, I’d warn against long key presses, but I’m not aware of an Android keyboard that supports them.
Android solution only:
You could even keep your
onKeyPress = "submit();"if you really felt like it. Just remove the last line here.