Categories
JavaScript Answers

How to change select option and trigger events with JavaScript?

Spread the love

Sometimes, we want to change select option and trigger events with JavaScript.

In this article, we’ll look at how to change select option and trigger events with JavaScript.

How to change select option and trigger events with JavaScript?

To change select option and trigger events with JavaScript, we trigger the event manually.

For instance, we write

<select id="sel">
  <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" />

to add a select and input element.

Then we write

const select = document.querySelector("#sel");
const input = document.querySelector('input[type="button"]');

select.addEventListener("change", () => {
  alert("changed");
});

input.addEventListener("click", () => {
  select.value = 2;
  select.dispatchEvent(new Event("change"));
});

to select both elements with querySelector.

And then we listen for the change event on the select element with select.addEventListener.

Then we add a click event listener to the input button to set the select’s value when it’s clicked and trigger the change event on it with dispatchEvent.

Conclusion

To change select option and trigger events with JavaScript, we trigger the event manually.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.