How to Set Selected Value of Dropdown in JavaScript

In this article, we are going to learn how to set selected value of dropdown in JavaScript for dynamic dropdown selection on HTML webpage.

Set Selected Value of Dropdown in JavaScript

Generally, while using various APIs and in some complex forms, we need to dynamically set ‘Selected’ value of dropdown list using JavaScript.

The given below JavaScript code will help us to understand the process of selecting default value in a dropdown list dynamically.

<html>
	<head>
		<title>errorsea - Dynamic Dropdown Select Option</title>
	</head>
	<body>
		<select id="my_menu"></select>
		<script>
			var values = ["PHP", "JavaScript", "HTML", "CSS"];
			
			function select_default(my_option, all_options, dropdown_id){
				var temp = "";
				for(var i = 0; i < all_options.length; i++){
					if(my_option == all_options[i]){
						temp += "<option value='"+all_options[i]+"' selected>"+all_options[i]+"</option>";
					}else{
						temp += "<option value='"+all_options[i]+"'>"+all_options[i]+"</option>";
					}
				}
				document.getElementById(dropdown_id).innerHTML = temp;
			}
			select_default("HTML", values, "my_menu");
		</script>
	</body>
</html>

Explanation

  • Here, we have created a JavaScript function named select_default()
  • In this function, we have passed three parameters. my_option, all_options, and dropdown_id
  • my_option is the value that we want to be selected as default.
  • all_options is the array of all available options for the dropdown list.
  • my_menu is the id of our select option where we want to select the default value.

Read Also: HTML Interview Questions and Answers

Conclusion

I hope now you have a complete understanding of how to set selected value of dropdown in javascript. We can do some more modifications to the above function for some more advancements.

Happy Scripting πŸ™‚

Leave a Reply

Your email address will not be published. Required fields are marked *