Reputation: 4479
I can use jquery to easily catch a change event of a select option when a user clicks it, however if javascript changes the select value, the 'change' event never triggers and needs to be manually triggered.
Is it possible to catch the value changing without manually having to trigger('change')
?
Example fiddle here: https://jsfiddle.net/1fhbha4o/1/
Upvotes: 0
Views: 179
Reputation: 1075159
Is it possible to catch the value changing without manually having to
trigger('change')
?
No. No event is fired when JavaScript code sets the value of a select. So your options are:
Have a common function you call both in response to a change
event and also whenever your code changes the value (perhaps centralize changing the value so you don't forget to call it).
.trigger('change')
Polling the value to see if it changes (blech).
Re #1 and #2, you could give yourself a valWithNotify
:
$.fn.valWithNotify = function(arg) {
if (arguments.length == 0) {
return this.val();
}
return this.each(function() {
$(this).val(arg).trigger("js-change"); // or just "change", but I'm not a
// fan of synthetic user events
});
};
Upvotes: 3