Home > OS >  Why isn't this onchange event triggering?
Why isn't this onchange event triggering?

Time:11-03

I am trying to detect when a <select> element that was dynamically added has had its option changed. However, it does not trigger when I change it.

The code:

var diP = document.createElement("select");


diP.add(option);
diP.add(option2);

diP.addEventListener("change", alert("Test"));

div2.appendChild(diP);


The code does not alert anything when I change the option.

CodePudding user response:

You need to pass callback as argument to event listener, among with event type.

diP.addEventListener("change", () => alert("Test"));

Also, please check if you've selected HTML element div2 correctly.

HTML:

<div > ... </div>

JS:

const div2 = document.querySelector('.div2')

CodePudding user response:

For addEventListener's, you need to pass the name of the function, not call the function. Or you can pass it an anonymous function.

function funcName(){

}

diP.addEventListener("change", funcName);

or

diP.addEventListener("change", function(){
   console.log(this.value)
});

CodePudding user response:

I assume that instead you see one alert when your script executes for the first time because instead of passing a function to the addEventListener you call it.

In order to have alert shown when input changes, you need to pass a function which runs in response to the change event. So your code should look like this:

....
diP.addEventListener("change", () => alert("Test"));
...

This way you say "run a function which will make an alert each time input changes".

  • Related