Change <select>'s option and trigger events with JavaScript
Solution 1:
Unfortunately, you need to manually fire the change
event. And using the Event Constructor will be the best solution.
var select = document.querySelector('#sel'),
input = document.querySelector('input[type="button"]');
select.addEventListener('change',function(){
alert('changed');
});
input.addEventListener('click',function(){
select.value = 2;
select.dispatchEvent(new Event('change'));
});
<select id="sel" onchange='alert("changed")'>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3' selected>Three</option>
</select>
<input type="button" value="Change option to 2" />
And, of course, the Event
constructor is not supported in IE. So you may need to polyfill with this:
function Event( event, params ) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent( 'CustomEvent' );
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
return evt;
}
Solution 2:
Fiddle of my solution is here. But just in case it expires I will paste the code as well.
HTML:
<select id="sel">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
<input type="button" id="button" value="Change option to 2" />
JS:
var sel = document.getElementById('sel'),
button = document.getElementById('button');
button.addEventListener('click', function (e) {
sel.options[1].selected = true;
// firing the event properly according to StackOverflow
// http://stackoverflow.com/questions/2856513/how-can-i-trigger-an-onchange-event-manually
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
sel.dispatchEvent(evt);
}
else {
sel.fireEvent("onchange");
}
});
sel.addEventListener('change', function (e) {
alert('changed');
});