Mo.
Mo.

Reputation: 42583

how can i retrieving text from input field as its entered in JavaScript??

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

Upvotes: 4

Views: 565

Answers (4)

Andy E
Andy E

Reputation: 344803

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.


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.

Upvotes: 10

Mr.RoyDiibs
Mr.RoyDiibs

Reputation: 148

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.

Upvotes: 1

Sam
Sam

Reputation: 1514

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

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

Upvotes: 1

rhino
rhino

Reputation: 13921

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>

Upvotes: 2

Related Questions