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 ?
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>
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
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");
});
});
Trigger change event
$("#reset").on("click", function () {
document.getElementById('my_select').selectedIndex = 0;
$("#my_select").change()
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.