danial
danial

Reputation: 1

How to execute change event on select when option change?

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?

Upvotes: 0

Views: 3115

Answers (2)

Daniel De Le&#243;n
Daniel De Le&#243;n

Reputation: 13679

This work for me:

document.getElementById('selct').dispatchEvent(new Event('change'));

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115282

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?

Upvotes: 0

Related Questions