0

I'm working on a project where I want to call a function whenever an option has been selected. Ideally, I would like to do something like this in my for loop but I have yet to find the correct event listener.

var s = document.getElementById("select");

for(var i = 0; i < 5; i++){
    var o = document.createElement('option');
    o.text = i;
    o.setAttribute("value", i);
    o.addEventListener("EVENT FOR BEING SELECTED", read);
    s.add(o);
}

function read(){
    console.log("Hello World!");
}

The purpose for this is to create a variable that keeps track of whatever option is selected. This would include the default selected option when the page has loaded which is why I didn’t want to use a click event listener.

  • 1
    Use the `change` event on the `select` element, then you can either check the selected option through the `.value` property of the `select` element or the `.selectedIndex` property. Maybe [this](https://stackoverflow.com/questions/67001384/how-do-i-create-an-element-if-the-option-in-select-tag-is-selected/67002478#67002478) answer can help a little. – Alain Doe May 05 '21 at 07:44
  • I did use the "change" event initially, but my main issue with "change" was that it doesn't can't call the function with the default option selected because loading the page and giving the select element its default option doesn't count as "change". – SnowKingJay100 May 05 '21 at 07:54
  • 1
    You need to initialize that variable then. The event which should trigger you to do the initialization is `DOMContentLoaded` and you would listen to it on `document`. – connexo May 05 '21 at 08:01

1 Answers1

0

Change event might work. If you want the event to trigger after was element added.

o.dispatchEvent(new Event('change'));