How can I change an HTML <select>
's option with JavaScript (without any libraries like jQuery), while triggering the same events as if a user had made the change?
For example using following code, if I change the option with my mouse then an event triggers (i.e. onchange
is run). However, when I change the option using JavaScript then it doesn't fire any event. Is it possible to fire trigger associated event handlers like onclick
, onchange
, etc., when an option is selected with JavaScript?
<select id="sel" onchange='alert("changed")'>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
<input type="button" onclick='document.getElementById("sel").options[1].selected = true;' value="Change option to 2" />
http://jsfiddle.net/xwywvd1a/
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…