下拉菜单未调用onChange函数

时间:2019-07-03 13:17:05

标签: javascript jquery html onclick onchange

我有一个按钮,单击该按钮会将下拉菜单重置为其默认选项。

我有一个用于下拉菜单的onchange事件监听器。 当我单击按钮时,事件监听器没有被触发。

HTML代码

<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");
});

单击x时,上面的更改代码不会触发,而在手动更改时会被触发。 我希望它适用于document.getElementById('Typess')。selectedIndex = 1;也一样 如何进行这项工作?

4 个答案:

答案 0 :(得分:2)

该事件change被触发,因为用户对该元素进行了更改。

另一种可能是手动触发该事件,如下所示:

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>

答案 1 :(得分:0)

尝试一下:

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

还请确保您确实更改了该值,而不要尝试设置相同的值

答案 2 :(得分:0)

尝试在change中实现您的click事件:

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

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

答案 3 :(得分:0)

触发更改事件

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