javascripthtmldomhtml-selectdom-events

Change <select>'s option and trigger events with JavaScript


How can I change an HTML <select>'s option with JavaScript (without any libraries like jQuery), while triggering the same events as if a user had made the change?

For example using following code, if I change the option with my mouse then an event triggers (i.e. onchange is run). However, when I change the option using JavaScript then it doesn't fire any event. Is it possible to fire trigger associated event handlers like onclick, onchange, etc., when an option is selected with JavaScript?

<select id="sel" onchange='alert("changed")'>
  <option value='1'>One</option>
  <option value='2'>Two</option>
  <option value='3'>Three</option>
</select>
<input type="button" onclick='document.getElementById("sel").options[1].selected = true;' value="Change option to 2" />


Solution

  • Unfortunately, you need to manually fire the change event. And using the Event Constructor will be the best solution.

    var select = document.querySelector('#sel'),
        input = document.querySelector('input[type="button"]');
    select.addEventListener('change',function(){
        alert('changed');
    });
    input.addEventListener('click',function(){
        select.value = 2;
        select.dispatchEvent(new Event('change'));
    });
    <select id="sel" onchange='alert("changed")'>
      <option value='1'>One</option>
      <option value='2'>Two</option>
      <option value='3' selected>Three</option>
    </select>
    <input type="button" value="Change option to 2" />

    And, of course, the Event constructor is not supported in IE. So you may need to polyfill with this:

    function Event( event, params ) {
        params = params || { bubbles: false, cancelable: false, detail: undefined };
        var evt = document.createEvent( 'CustomEvent' );
        evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
        return evt;
    }