How can i retrieve the contents of an input field as they are entered with JavaScript?
i know .onChange only works after the focus is changed from the input field?
thanks
EDIT: since writing this answer, I learned of the HTML5 oninput
event which is much more appropriate than key events because it will detect all forms of input including paste, drag and drop, etc. The event is supported in all major browsers except IE 8 and lower, but you can simulate the event in IE by mapping to onpropertychange
instead. Example:
if ("onpropertychange" in myInput && !("oninput" in myInput)) {
myInput.onpropertychange = function () {
if (event.propertyName == "value")
myHandler.call(this, event);
}
}
else
myInput.oninput = myHandler;
Note that onpropertychange
doesn't fire when inputting into non-form elements with the contentEditable
property set.
myInput.onkeydown = function () {
var self = this;
window.setTimeout(function () {
alert(self.value);
},0);
}
Example: http://jsfiddle.net/fgcYD/
Note that this won't catch pasting or dragging and dropping text into the box. For those you need other events.
You should try the onKeyUp event. Here's a simple example:
<input type="text" onkeyup="document.getElementById('xyz').innerHTML=this.value">
<div id="xyz"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With