2

In JavaScript, I need to detect when the value of a certain select element has changed for any reason, including programmatically.

The onchange event is only fired when the user changes the selected value manually, not when other JavaScript changes the value programmatically.

This is a website with a variety of plugin components that we don't want to hack up (and in some cases can't hack up, since the code resides on other sites). So triggering the change event myself whenever there is a programmatic change isn't an option. I need to actually monitor the select, listen to it, for a change in value.

Is this possible? I haven't found a way.

Is there perhaps some library I can use to frequently poll the value looking for change? Or some other way?

Greg Holmes
  • 141
  • 13
  • 3
    Trigger the `change` event when you programattically change the value. Something like `.val('something').change();` – Selvakumar Arumugam Oct 17 '13 at 16:26
  • 2
    Use the object.watch implementation from this answer http://stackoverflow.com/questions/1759987/listening-for-variable-changes-in-javascript-or-jquery – Udan Oct 17 '13 at 16:28

2 Answers2

3
var targetSelect = $('appropriate selector');
var lastVal = targetSelect.val();

setInterval(function() {
    var newVal = targetSelect.val();
    if(newVal !== lastVal) {
        // it changed, fire an event or process it
    }
    lastVal = newVal;
}, intervalSpacing);

The lower the value you pass to 'intervalSpacing' the more CPU time you spend, but the sooner you realize it changed. Tune cautiously.

Mike Edwards
  • 3,642
  • 15
  • 21
-1

You can use the MutationObservers API to watch for changes to the DOM:

https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

You might have to actually observe the option nodes for the selected attribute, instead of watching the parent select node, but it should be just as easy.

Tibos
  • 26,262
  • 4
  • 43
  • 59