Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically click Select element and trigger onChange handler?

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.

like image 811
Kael Vergara Avatar asked Mar 22 '17 06:03

Kael Vergara


Video Answer


3 Answers

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>
like image 106
Mosd Avatar answered Sep 17 '22 11:09

Mosd


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>
like image 40
Vara Prasad Avatar answered Sep 18 '22 11:09

Vara Prasad


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>
like image 20
CC12 Avatar answered Sep 19 '22 11:09

CC12