tags:

views:

62

answers:

4

Hi

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

+4  A: 

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>
rhino
onkeyup will *only* give you the value when the key is lifted. Holding the key down will repeat the input but the keyup event will not fire.
Andy E
@Andy E: Yes, but if you use only onkeydown, the value returned from the text field will not be full. I mean the last entered character will always be missing.
rhino
@rhino: not if you use a timer - see my answer and the example in it.
Andy E
+2  A: 

If your input field has focus, use the onKeyUp event to monitor the user typing text.

http://www.w3schools.com/jsref/event_onkeyup.asp

Sam
+5  A: 

onkeyup will only fire after the key is lifted, so for best results use onkeypress and/or onkeydown. If you use a timer with a delay of 0ms, you can get the new value immediately after it is updated:

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.

Andy E
works with ctrl-v though (keydown)
Litso
+1 that is best answer here
Sarfraz
+1  A: 

Once I had used a combination of "onKeyup", "onBlur", onKeyPress to handle all the circumstances while making a TextBox to allow only numeric values. Like this:

//C#    
tc.Attributes.Add("onKeyup", "extractNumber(this,-1,true);"); tc.Attributes.Add("onBlur", "extractNumber(this,-1,true,true);"); tc.Attributes.Add("onKeyPress", "return blockNonNumbers(this, event, true, true);");

with this .js code: http://www.mredkj.com/tutorials/validate2.js

And it still works pretty well.

Mr.RoyDiibs