0
votes

I have a button , which when clicked resets the dropdown menu to its default option.

I have a onchange event listener for the drop down menu. The event listener is not getting triggered when I click the button.

HTML CODE

<select id="my_select">
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
</select>
<div id="reset">reset</div>
$("#reset").on("click", function () {
document.getElementById('my_select').selectedIndex = 0;
});
$("#my_select").change(function(){
alert("Hi");
});

The above on change code is not triggering when x is clicked, whereas it is getting triggered when manually changed. I expect it to work for document.getElementById('Typess').selectedIndex = 1; as well. How to make this work ?

4
Can you please provide a more elaborate code sample? This is something we need to be able to answer your question.StefanN
onchange only fires when the user makes a change. I am too lazy to find the dupe.epascarello

4 Answers

2
votes

That event change is triggered because a user made a change on that element.

An alternative could be triggering that event manually as follow:

let $typess = $("#Typess")
$(".x").click(function(event) {
  document.getElementById('Typess').selectedIndex = 1;
  $typess.trigger("change");
})

$typess.on('change', function(event) {
  console.log("Changed");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="Typess">
<option>A</option>
<option>B</option>
</select>
<p>
<button class="x">Click me!</button>
0
votes

try this:

    $(".x").click(function(event){
    // alert(" x is clicked") (This alert is working)
     document.getElementById('Typess').val(1);
    })

Also make sure you do change the value, and not try to set the same value

0
votes

Try to implement your change event within the click one:

$("#reset").on("click", function () {
document.getElementById('my_select').selectedIndex = 0;

  $("#my_select").change(function(){
  alert("Hi");
  });
});
0
votes

Trigger change event

$("#reset").on("click", function () {
document.getElementById('my_select').selectedIndex = 0;
$("#my_select").change()
});