Skip to content Skip to sidebar Skip to footer

Javascript - How To Detect A Programmatic Value Change On A Select Element (dropdown)

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 ch

Solution 1:

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.

Solution 2:

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.

Post a Comment for "Javascript - How To Detect A Programmatic Value Change On A Select Element (dropdown)"