Javascript Text Field Event

I ran into a problem with the type of text input (i.e. a text box).

I wrote a function used by the onkeyup event in a text box. The line looks like this:

 <input type='TEXT' value='abc' onkeyup='changeSomething( this );'> 

But now I am facing a problem when the user selects values โ€‹โ€‹from previously entered values, I do not receive any event when the user selects any previously entered values โ€‹โ€‹from the drop-down list (editing: I believe that it refers to browser autocomplete here).

Does anyone have a solution for this? :)

+6
javascript textbox
source share
2 answers

use onchange instead of onkeyup in this case

see http://www.w3schools.com/jsref/event_onchange.asp

eg.

 <input type='text' value='abc' onchange='changeSomething(this);' /> 

to get around this

EDIT Two things:
1) Autocomplete values โ€‹โ€‹can be selected using the arrow keys and the enter / tab, as well as with the mouse. The /enter.tab arrow keys fire onkeyup events ... clicking in the autocomplete field does not fire the onclick event.
2) The onchange event fires as soon as the focus is lost if the content has changed. Focus is not lost when auto-fill values โ€‹โ€‹are selected.

Essentially, there seems to be no way to reasonably guarantee that the event will be handled the way you want.

First, do you really need to listen to every keystroke? Secondly, would you rather turn off autocomplete? (e.g. <input type='text' value='abc' autocomplete='off' onkeyup='changeSomething(this);' /> )

+11
source share

Here's a solution that periodically polls an item for any changes

 <script type="text/javascript"> var changeWatcher = { timeout: null, currentValue: '', watchForChange: function( el ) { if( el.value != this.currentValue ) { this.changed( el ); } this.timeout = setTimeout( function() { changeWatcher.watchForChange(el) }, 200 ); }, cancelWatchForChange: function() { clearTimeout( this.timeout ); this.timeout = null; }, changed: function( el ) { this.currentValue = el.value; // do something with the element and/or it value //console.log( el.value ); } } </script> <input type='text' value='abc' onfocus='changeWatcher.watchForChange(this)' onblur='changeWatcher.cancelWatchForChange()' onchange='changeWatcher.changed(this)' /> 
+3
source share

All Articles