Diskdrive
Diskdrive

Reputation: 18825

How can I know when the available options in a select box changes

I have a select box on my page where the options dynamically change:

<select size="6" multiple="multiple" >
    <option value="1">Id</option>
    <option value="2">Subject</option>
    <option value="3">Status</option>
    <option value="4">Assignment</option>
    <option value="5">LastCreatedBy</option>
</select>

When it changes I would like to refresh some text elsewhere on the screen based on the displayed options.

The problem is I can't seem to find an event that is thrown for when an option is added or deleted.

How may I be notified when the number of options in a select box changes.

Upvotes: 1

Views: 63

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074208

You can use a MutationObserver to watch the select element for changes to its contents:

var ob = new MutationObserver(function() {
  snippet.log("Changed");
});
ob.observe(document.getElementById("foo"), {
  subtree: true,
  childList: true
});
setTimeout(function() {
  document.getElementById("foo").options.add(new Option("Hi"));
}, 100);
<select id="foo"></select>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

MutationObserver is well-supported except for IE, which didn't get them until IE11. But IE supported the old mutation events; you can find shims/polyfills that use the old events to provide the new interface (or just use the old events directly if typeof MutationObserver === "undefined"). I don't know whether the old events were fired by IE when you change the options in a select, though, you'll need to check.

As a last resort if there is no MutationObserver and mutation events don't work, poll. Polling every 50ms or so shouldn't have any significant impact on the performance of your page.

Upvotes: 3

Related Questions