I am looking for a way (or a workaround) to subscribe for selectedIndex
changing (on <select>
element) when the change done by a simple assignment (like myElement.selectedIndex=1
).
<select id = "mySelect" onchange="myListener()">
<option>0</option>
<option>1</option>
</select>
<script>
function myListener() {
console.log('Yes, I hear...'); // doesn't work on selectedIndex assignment
}
document.getElementById('mySelect').selectedIndex = 1;
</script>
Seems it's not possible, but maybe there is some workaround.
dispatchEvent
is not an option (the listener attachment must be done from outside).
My only solution so far, very similar to @jren510 (but I like his solution more).
function myListener() {
console.log('Yes, I hear...');
}
const originalPropDescriptor = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'selectedIndex');
Object.defineProperty(HTMLSelectElement.prototype, 'originalSelectedIndex', originalPropDescriptor);
Object.defineProperty(HTMLSelectElement.prototype, 'selectedIndex', {
get() {
return this.originalSelectedIndex;
},
set(value) {
myListener();
this.originalSelectedIndex = value;
}
});
I would like to avoid overriding native methods, by so far it's the only way I see.