Cheitan Cheitan - 5 months ago 18
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(){
console.log(selectList.options[selectList.selectedIndex].value);
});


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(){
console.log(selectList.options[selectList.selectedIndex].value);
});


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

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() {
  console.log(this.value);
});

var event = new Event('change');
document.getElementById('mySelect').dispatchEvent(event);
<select id="mySelect">
  <option>Apple</option>
  <option>Orange</option>
  <option>Pineapple</option>
  <option>Banana</option>
</select>

Comments