I have found lots of useful examples of how to set up a HTML "select" form. What I can not find anywhere, is how to "auto-trigger" the default option, without having to "select" it first from drop-down.
2 Answers
Since you have already defined onchange event for select element, you can call .onchange() to trigger onchange event of the select element.
Sample code below:
<form>
<select name="fruit" onchange="showFruit(this.value)">
<option>Choice:</option>
<option value="1">Yellow Fruit</option>
<option value="2">Red Fruit</option>
</select>
</form>
<script>
window.onload = function () {
var el = document.getElementsByName('fruit')[0];
el.value = 1; //Set default value
el.onchange(); //trigger onchange event
}
function showFruit(val) {
alert(val);
}
</script>
2 Comments
Phani Kumar M
window.onload is JavaScript and you need to include all the code above inside <script></script> tags. Updated code above.butterfly
It works, Phani!! Absolutely perfect!! Thank you very much! Will mark this as accepted! And also thank you to HBK for the previous answer!
Do this in the onload() method:
Var select = document.getElementsByName('fruit')[0];
select.value=1;
select.dispatchEvent(new Event('change'));
This shall change the selected option to 1 (or any other as you would like) on page load and also fire the onchange event which shall populate your table.
2 Comments
HBK
@butterfly here you go... mobile.htmlgoodies.com/beyond/javascript/article.php/3724571/… . Although I would suggest you brush up your JavaScript basics knowledge a bit. Regards.
butterfly
As soon as I accumulate my 15 reputation points, will do! :-) Thanks again! :-)