0

How can I execute the onchange event handler on select when I change the option?

document.getElementById('selct').value=2;
<select id="selct" onchange="alert('change success')">
  <option value="0">val1</option>
  <option value="1">val2</option>
  <option value="2">val3</option>
  <option value="3">val4</option>
  <option value="4">val5</option>
  <option value="5">val6</option>
</select>

When I do that, the result is val3, but select's onchange didn't work. How can I fix it?

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
danial
  • 1

2 Answers2

1

Changing value programmatically using Javascript doesn't fire change event. To make it work you have to fire the event programmatically.

var sel = document.getElementById('selct');
sel.value=2;
sel.onchange();

var sel = document.getElementById('selct');
sel.value = 2;
sel.onchange();
<select id="selct" onchange="alert('change success')">
  <option value="0">val1</option>
  <option value="1">val2</option>
  <option value="2">val3</option>
  <option value="3">val4</option>
  <option value="4">val5</option>
  <option value="5">val6</option>
</select>

From MDN docs, change events for select tag fires when:

When the user commits the change explicitly (e.g. by selecting a value from a 's dropdown with a mouse click, by selecting a date from a date picker for , by selecting a file in the file picker for , etc.);

Refer : How can I trigger an onchange event manually?

Pranav C Balan
  • 110,383
  • 23
  • 155
  • 178
0

This work for me:

document.getElementById('selct').dispatchEvent(new Event('change'));
Daniel De León
  • 12,505
  • 5
  • 78
  • 69