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.
Asked
Active
Viewed 3,136 times
2 Answers
1
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>
Phani Kumar M
- 4,564
- 1
- 14
- 26
-
`window.onload` is JavaScript and you need to include all the code above inside `` tags. Updated code above. – Phani Kumar M Oct 11 '17 at 01:11
-
It works, Phani!! Absolutely perfect!! Thank you very much! Will mark this as accepted! And also thank you to HBK for the previous answer! – butterfly Oct 11 '17 at 01:15
0
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.
HBK
- 735
- 1
- 11
- 29
-
@butterfly here you go... https://mobile.htmlgoodies.com/beyond/javascript/article.php/3724571/Using-Multiple-JavaScript-Onload-Functions.htm . Although I would suggest you brush up your JavaScript basics knowledge a bit. Regards. – HBK Oct 11 '17 at 00:56
-
1As soon as I accumulate my 15 reputation points, will do! :-) Thanks again! :-) – butterfly Oct 13 '17 at 06:53