Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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>

Solution 2:

You can use trigger function of jQuery.

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


setTimeout(function(e){ $("#select1").val(2).trigger('change'); }, 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 3:

.. or using VanillaJS (favoring event constructors over createEvent):

function setSelectedIndex(el, index){
   el.selectedIndex = index;
   el.dispatchEvent(new Event('change', { bubbles: true }));
}

setSelectedIndex(select1, 2);

Post a Comment for "Setting Selectedindex Not Triggering Onchange Event"