For example, with the following code. I tried several solutions.
function handleChange() {
    alert('hello')
}
<select id="names" onchange="handleChange()">
    <option>Foo</option>
    <option>Bar</option>
</select>
Solution 1.
document.getElementById('#select').selectedIndex = 1
This would change the value and display of select but doesn't trigger handleChange();
Solution 2
var element = document.getElementById('names');
var event = new Event('change');
element.dispatchEvent(event);
This returns true but still doesn't trigger handleChange();
Any ideas on how to do this? Or can it actually be done? Solution has to be javascript/html only and sadly no jQuery.
try this, it worked for me...your problem can just be you didnt change the actual value on solution 2 before triggering change :
    function handleChange() {
        alert('hello')
    }
 console.log(document.getElementById('names'));
 document.getElementById('names').selectedIndex = 1;
 document.getElementById('names').dispatchEvent(new Event('change'));
    <select id="names" onchange="handleChange()">
        <option>Foo</option>
        <option>Bar</option>
    </select>
Strange @KaelVergara, I copied your code and it is working for me
<script>
function handleChange123() {
    alert('hello')
}
</script>
<select id="names123" onchange="handleChange123()">
    <option>Foo</option>
    <option>Bar</option>
</select>
<script>
var element = document.getElementById('names123');
var event = new Event('change');
element.dispatchEvent(event);
</script>
                        TRY THIS:
 function handleChange()
 {
       alert('hello')
 }
window.onload = function()
 {
   document.getElementById('names').selectedIndex = 1;
   handleChange();
 }
   <select id="names" onchange="handleChange()>
     <option>Foo</option>
     <option>Bar</option>
    </select>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With