There are many ways the value of a <input type="text">
can change, including:
- keypresses
- copy/paste
- modified with JavaScript
- auto-completed by browser or a toolbar
I want my JavaScript function to be called (with the current input value) any time it changes. And I want it to be called right away, not just when the input loses focus.
I'm looking for the cleanest and most robust way to do this across all browsers (using jQuery preferably).
Example use case: On the Twitter Signup page, the username field's value gets shown in the url "http://twitter/username" below it.
2017 answer: the input event does exactly this for anything more recent than IE8.
A real-time fancy solution for jQuery >= 1.9
if you also want to detect "click" event, just:
if you're using jQuery <= 1.4, just use
live
instead ofon
.Unfortunately there is no event or set of events that matches your criteria. Keypresses and copy/paste can both be handled with the
keyup
event. Changes through JS are trickier. If you have control over the code that sets the textbox, your best bet is to modify it to either call your function directly or trigger a user event on the textbox:If you don't have control over that code, you could use
setInterval()
to 'watch' the textbox for changes:This sort of active monitoring won't catch updates 'immediately', but it seems to be fast enough that there is no perceptible lag. As DrLouie pointed out in comments, this solution probably doesn't scale well if you need to watch lots of inputs. You can always adjust the 2nd parameter to
setInterval()
to check more or less frequently.you can see this example and choose which are the events that interest you:
I have created a sample. May it will work for you.
http://jsfiddle.net/utbh575s/
This jQuery code catches immediate changes to any element, and should work across all browsers: