Search code examples
javascriptjqueryselect

Setting selectedindex not triggering onchange event


I am trying to change selectedindex of a select tag. But onchange event is not triggered while changing the index via jquery.

I am creating option for the select tag dynamically. I won't be knowing the values of option tag.

Is there any other method to achieve it? Here is my code snippet. Feel free to give inputs.

function callFunc(obj) {
  console.log(obj.value);
}

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>


Solution

  • You need to trigger the change yourself calling change() on the element. I have replaces the selectedIndex with val function's call. Also attach event handler using javascript, not via markup.

    const select = $("#select1");
    
    select.on('change', function() {
      console.log(this.value);
    });
    
    setTimeout(() => {
      select.val(2).change();
    }, 2000);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select id="select1">
      <option value='0'>select ....</option>
      <option value='1'>1</option>
      <option value='2'>2</option>
      <option value='3'>3</option>
    </select>