8

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.

Kael Vergara
  • 198
  • 1
  • 1
  • 10

4 Answers4

13

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>
Mosd
  • 1,578
  • 18
  • 21
1

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>
Vara Prasad
  • 487
  • 2
  • 10
1

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>
CC12
  • 11
  • 1
0

one way would be as below from the below answer for another question here
Trigger change() event when setting <select>'s value with val() function

 $('#selectField').val(10).change();

or simple one just to trigger the event

 $('#selectField').change();

or if you do not want to use Jquery you can use the below method

 const $roomID = document.querySelector('.roomID')
$roomID.onchange = function () {
   if ($("#ddlRoom").val() !== "") {
       var ID = $("#ddlRoom").val();
       console.log(ID);
} ;
};

$roomID.dispatchEvent(new Event('change'));
Ali
  • 934
  • 13
  • 20