Setting Selectedindex Not Triggering Onchange Event
I am trying to change selectedindex of a select tag. But onchange event is not triggered while changing the index via jquery. I am creating option for the select tag dynamically.
Solution 1:
You need to trigger the change yourself calling change()
on the element. I have replaces the selectedIndex
with val
function's call. Also attach event handler using javascript, not via markup.
const select = $("#select1");
select.on('change', function() {
console.log(this.value);
});
setTimeout(() => {
select.val(2).change();
}, 2000);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="select1"><optionvalue='0'>select ....</option><optionvalue='1'>1</option><optionvalue='2'>2</option><optionvalue='3'>3</option></select>
Solution 2:
You can use trigger function of jQuery.
functioncallFunc(obj) {
console.log(obj.value);
}
setTimeout(function(e){ $("#select1").val(2).trigger('change'); }, 2000)
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="select1"onchange="callFunc(this);"><optionvalue='0'>select ....</option><optionvalue='1'>1</option><optionvalue='2'>2</option><optionvalue='3'>3</option></select>
Solution 3:
.. or using VanillaJS (favoring event constructors
over createEvent
):
functionsetSelectedIndex(el, index){
el.selectedIndex = index;
el.dispatchEvent(newEvent('change', { bubbles: true }));
}
setSelectedIndex(select1, 2);
Post a Comment for "Setting Selectedindex Not Triggering Onchange Event"