Warm tip: This article is reproduced from stackoverflow.com, please click
html javascript jquery onchange onclick

onChange function not getting invoked for dropdown menu

发布于 2020-03-27 10:16:53

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 ?

Questioner
Adithya Viswanathan
Viewed
160
Ele 2019-07-03 21:24

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>