trigger change (and beforechange) when selectedIndex is modified
..a simple VanillaJS function:
// equivalent to jquery: $(el).val(index).trigger('change');
function setSelectedIndex(el, index){
el.selectedIndex = index;
el.dispatchEvent(new Event('change', { bubbles: true }));
}
// sample call - setSelectedIndex(select1, 2)
setTimeout(setSelectedIndex, 2000, select1, 2);
... or if you want to make this a general feature for all select elements (present and future):
// put this somewhere central
(function selectedIndexWithEvents(proto, selectedIndex) {
const original = Object.getOwnPropertyDescriptor(proto, selectedIndex);
if (!original || !original.set) return;
Object.defineProperty(proto, selectedIndex, {
get() { return original.get.call(this); },
set(value) {
if (this[selectedIndex] === value) return; // unchanged
if (this.dispatchEvent(Object.assign(new Event('beforechange', { bubbles: true, cancelable: true }), { newValue: value })).defaultPrevented) return; // preventDefault(true)
original.set.call(this, value);
this.dispatchEvent(new Event('change', { bubbles: true }));
}
});
})(HTMLSelectElement.prototype, "selectedIndex");
// your sample call now will trigger beforechange and change
function callFunc(el){ console.log('changez', el); }
setTimeout(() => { $("#select1")[0].selectedIndex = 2; }, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select1" onchange="callFunc(this);">
<option value='0'>select ....</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
dinamically?