How can I get text from an input field since it is entered in JavaScript?

How can I get the contents of an input field when typing with JavaScript?

I know .onChange only works after changing the focus from the input field?

thanks

+4
source share
4 answers

You should try the onKeyUp event. Here is a simple example:

<input type="text" onkeyup="document.getElementById('xyz').innerHTML=this.value"> <div id="xyz"></div> 
+3
source

EDIT: after writing this answer, I found out about the HTML5 oninput event, which is much more suitable than key events, because it will define all input forms, including insert, 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 matching it with onpropertychange . Example:

 if ("onpropertychange" in myInput && !("oninput" in myInput)) { myInput.onpropertychange = function () { if (event.propertyName == "value") myHandler.call(this, event); } } else myInput.oninput = myHandler; 

Please note that onpropertychange does not start when entering informal elements with the contentEditable property contentEditable . See my blog for more information.

<h / "> onkeyup will only work after the key is raised, so use onkeypress and / or onkeydown for best results. If you use a timer with a delay of 0 ms, you can get a new value immediately after updating it:

 myInput.onkeydown = function () { var self = this; window.setTimeout(function () { alert(self.value); },0); } 

Example: http://jsfiddle.net/fgcYD/

Note that this will not insert or drag text into the field. For those who need other events.

+10
source

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

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

+1
source

Once I used the combination of "onKeyup", "onBlur", onKeyPress to handle all circumstances, making the TextBox only accept numerical 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 very well.

+1
source

All Articles