4
votes

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.

4
Have you done any research into "javascript event handlers" or jquery event handlers? What specifically have you tried and what issues are you running into?scrappedcola
Please check my answer.ppianist
@scrappedcola I've done research on both. I would like to use pure JavaScript since I'm not able to add a Jquery libraryMariton
@scrappedcola I updated my question to include a code example.Mariton

4 Answers

7
votes

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>
1
votes
document.getElementById("a_background").addEventListener("change", function(){
     var e = document.getElementById("a_background");
     var selected = e.options[e.selectedIndex].text;
     if(selected =='yes')
        doSomething();
});
0
votes

Try use onchange="myFunction()" instead of onChange="myFunction()"

function myFunction()
{
  console.log(document.getElementById("a_background").value == 1 ? 'Yes selected' : 'No selected');
}
<select id="a_background" name="background" class="widget" onchange="myFunction()">
 <option value="1">Yes</option>
 <option value="0" selected="selected">No</option>
</select>
0
votes

You can use jquery .change() function for this. Inside this function you can compare your value and do your operations accordingly.

Read Here

$(document).ready(function() {
  $("#a_background").change(function() {
    if ($(this).val() == "1") {
      console.log("Yes");
    } else {
      console.log("No");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select id="a_background" name="background" class="widget">
 <option value="1">Yes</option>
 <option value="0" selected="selected">No</option>
</select>