I would like to add an event listener to a select element and execute an action when an option is selected. My HTML code is:
<select id="a_background" name="background" class="widget">
<option value="1">Yes</option>
<option value="0" selected="selected">No</option>
</select>
So when Yes
is selected: do something, If No
is selected: do something else
Here is what I have so far:
var activities = document.getElementById("a_background");
var options = activities.querySelectorAll("option");
activities.addEventListener("changed", function() {
if (options == "addNew")
{
alert('add New selected');
}
else
{
alert('add None selected');
}
});
Due to restrictions I cannot call a function within the select element. For example <select onChange="myFunction()" id="a_background">
That is why I would like to add an event listener.
That could be simply done using the addEventListener()
function :
document.querySelector('#a_background').addEventListener("change", function() {
if (this.value == "1") {
console.log('Yes selected');
}else{
console.log('No selected');
}
});
<select id="a_background" name="background" class="widget">
<option value="1">Yes</option>
<option value="0" selected="selected">No</option>
</select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With