'Why addEventListener to 'select' element don not work?
I want select to another option ,it will console.log 2222 in Console,but when I choose to another,it don't console, so why?
let mySelect = document.getElementById('mySelect');
mySelect.addEventListener('change', print());
function print() {
console.log(2222);
}
<select id="mySelect">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
<option value="Volvo">Volvo</option>
</select>
Solution 1:[1]
In your code, when added event listener to the element document.getElementById('mySelect')
it is being executed the function print()
and that is why you see the result in the console..
What you want is to use the event listener callback.. In your case is the function print
, but should be used without the parentheses
Code:
document
.querySelector('#mySelect')
.addEventListener('change', print);
function print() {
console.log(2222);
}
<select id="mySelect">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
<option value="Volvo">Volvo</option>
</select>
Or your can use directly an ES6 Arrow function
Code:
document
.querySelector('#mySelect')
.addEventListener('change', () => console.log(2222));
<select id="mySelect">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
<option value="Volvo">Volvo</option>
</select>
Solution 2:[2]
While searching for a solution to the "addEventListener"-problem for change-triggers, i came to the following, very simple solution:
$("select").on("change", function(event){
console.log("ble");
validate(event.target);
checkWeiter();
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | h00ligan |