-1

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.

1

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

window.onload is JavaScript and you need to include all the code above inside <script></script> tags. Updated code above.
It works, Phani!! Absolutely perfect!! Thank you very much! Will mark this as accepted! And also thank you to HBK for the previous answer!
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.

2 Comments

@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.
As soon as I accumulate my 15 reputation points, will do! :-) Thanks again! :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.