I have a text input whose content is changed by a script not by user. So I would want to fire an event when the value changes. I can't find a suitable event for that. I even found this on StackOverflow, but it is not the solution I'm looking for.
How to make this work with jQuery and a text input where the value is set like this:
myTextControl.value = someValue
Here I want to fire an event to see the new value.
Yeah, there isn't one.
There are DOM Mutation Events, but they aren't supported well cross-browser, and don't fire for form values anyway as those aren't reflected in attributes (except in IE due to a bug).
In Mozilla only, a JavaScript watch could be set on the value property to catch scripted changes. In IE only, a JScript onpropertychange handler could be set to catch both scripted and user-driven changes. In other browsers you would have to use your own interval poller to look for changes.
This is highly unsatisfactory. It won't respond to user-driven changes in Mozilla, it allows only one watched property per object in IE, and in other browsers the handler function will get called much later in execution flow.
It's almost certainly better to rewrite the parts of script that set
value
to call a setValue wrapper function instead, that you can monitor for changes you want to trap.You'll need to listen to keyboard events when the element you're watching has focus.
You can add a normal event listener to your input field like so. (using jQuery)
Ok considering that the javascript which changes the input value isn't controlled by you it gets difficult. You are left with two options:
1.) Crossbrowser compatible: Implement polling of input value with a function which continuously checks if the value changed. (Something along these lines).
If the value can change multiple times by the external script just let the interval function run instead of canceling it and just update oldValue;
2.) AFAIK Not supported yet by all browsers (? test it on the ones you need to support)
You could bind to a special DOM Level 3Event:
DOMAttrModified
(in Firefox, maybe others too I think Opera has it too, Safari??, Chrome??) and in IE of course it has a different namepropertychange
(and is proprietary and different from the W3C behavior)Now ideally you could combine the two options and check if support for
DOMAttrModified
orpropertychange
is there and use accordingly or fallback to the polling solution.Reading links
W3C DOM Mutation Events
W3C DOMAttrModified Event
MSDN DHTML propertychange Event
jQuery CSS Property Monitoring Plug-in updated
Last link is some guy which basically already made a jQuery plugin doing the things described by me (untested by me, provided just as a reference)
You can also use some these event listener to your input field like
try this