Reputation: 45
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 ?
Upvotes: 0
Views: 840
Reputation: 1604
Trigger change event
$("#reset").on("click", function () {
document.getElementById('my_select').selectedIndex = 0;
$("#my_select").change()
});
Upvotes: 0
Reputation: 258
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");
});
});
Upvotes: 0
Reputation: 33726
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>
Upvotes: 2
Reputation: 53
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
Upvotes: 0