Cheitan Cheitan - 2 years ago 97
Javascript Question

What event to use with HTML's select tag

My question is about what event is better to use with the select tag in the case where I want to detect which option of the select is selected in JavaScript.

Until now I've found two way to do it. The first one is to use the "change" eventListener, just like this :

selectList.addEventListener("change", function(){

But there is two problem with this method. Firstly, this event is not fired at the beginning, so it don't log the very first element, selected by default in the list. Secondly, when clicking on an item of the list, the event is fired two times, which means there is two identical lines in the console.

The second method I've tried is with the "click" event, just like that :

selectList.addEventListener("click", function(){

The problem here is obviously that the event is fired each time I click on the list, so the log is done at least two times if I want to change the selected item. Furthermore, the default selected item when the list "spawn" is not logged either, which is normal.

So how can I do to log the selected item only once, and make the default selected item logged too ?

Answer Source

change event is invoked when option of the select-input is changed.

Create a new change-event using Eventconstructor and invoke dispatchEvent on the target element.

document.getElementById('mySelect').addEventListener("change", function() {

var event = new Event('change');
<select id="mySelect">

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download