lonewarrior556 lonewarrior556 - 4 months ago 14
HTML Question

Can I catch a js triggered change event?

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/

Answer

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:

  1. 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).

  2. .trigger('change')

  3. 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
    });
};