Should changes to the value of a SELECT control made in code trigger the onChange Event?
I'm using the following code to watch for changes to a given SELECT element.
someSelectElement.change(function () { alert('change made'); });
And it works peachy when I change the value the selected item through the UI.
However, It doesn't seem to trigger the event if the value is changed via a script. For example, the following code executed in the debugging console changes the selected item, but does NOT fire the event.
$('#someSelectElement').val('NewValue')
I know开发者_高级运维 it seems unusual to need to detect changes made to the control by the other code, and if it was my code I'd just manually trigger the event and call it a day. The trouble is, I am writing a jQuery plug-in that needs to do something when the value of a watched control changes whether it be through user intervention or some client-side script that the user of my plug-in is running.
I'm assuming the behavior of not triggering events in this situation is by design. If not, please speak up and let me know what I'm doing wrong. If so, is there a workaround where I can watch for changes made to the value of a SELECT element regardless of whether they were user or code initiated?
Code-driven changes to element values don't trigger native events. You can always trigger them yourself, of course, via the jQuery ".trigger()" method.
The Mozilla browsers have long had a "watch" feature, but that's not supported by other platforms.
Okay - so I might have a better solution to this than the interval timer solution.
Also note that this is a MUCH larger hack and the following is simply proof of concept and by no means is production-ready:
$(document).ready(function(){
function change(){
$('#test option[value=3]').attr('selected', 'selected');
}
// run it before changing it
alert('first go');
change();
var tmp = String(change).replace(/function change\(\){/, '');
tmp = tmp.replace('}', '');
tmp += 'alert(\'it changed\');';
change = function() { eval(tmp); };
// try it again - should get the second alert this time
alert('second go (post mod)');
change();
});
See the sample here.
Essentially, what I'm doing is:
- Convert the function to a string
- Replace the bounding function constructs
- Add whatever functionality I want to inject
- Reassign the modified function to the original function
Seems to work, but might not in the real world :)
精彩评论