1

I have a select tag that has an eventListener on change.

Now I also have two different buttons that change it, that uses:

      (selectTag).selectedIndex++;

The above does what I want to achieve, but it does not call my function callback on change.

How would I go about doing that? Other Approaches welcomed.

I would prefer pure-JS solutions, (noJquery please).

Secret
  • 3,291
  • 3
  • 32
  • 50

1 Answers1

3

Just trigger change event when calling click handler on buttons:

var select = document.querySelector("select");
var button = document.querySelector("button")

select.addEventListener("change", function (e) {
  alert(e.target.value)
});

button.addEventListener("click", function () {
  var event;

  try {
    event = new Event("change")
  } catch (e) {
    event =  document.createEvent("Event");
    event.initEvent("change", true, false);
  }

  select.selectedIndex++;
  select.dispatchEvent(event);
});

JS Bin

Update: I've changed it work in IE 10 and probably some others.