How to get text of an input text box during onKeyPress? How to get text of an input text box during onKeyPress? javascript javascript

How to get text of an input 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/


Handling the input event is a consistent solution: it is supported for textarea and input elements in all contemporary browsers and it fires exactly when you need it:

function edValueKeyPress() {    var edValue = document.getElementById("edValue");    var s = edValue.value;    var lblValue = document.getElementById("lblValue");    lblValue.innerText = "The text box contains: " + s;}
<input id="edValue" type="text" onInput="edValueKeyPress()"><br><span id="lblValue">The text box contains: </span>