Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an event listener to a select element?

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.

like image 740
Mariton Avatar asked Mar 08 '23 17:03

Mariton


1 Answers

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>
like image 121
Zakaria Acharki Avatar answered Mar 10 '23 11:03

Zakaria Acharki