How to Set Default Value in Dropdownlist in HTML Using JavaScript

Selecting a default value in a dropdown list is very easy. Here we are going to learn how to select default value in a dropdown list using JavaScript for dynamic content.

Default Value in Dropdownlist Using JavaScript

Generally, while using various APIs and in some complex forms, we need to dynamically select the dropdown list.

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.

Conclusion

I hope now you have a complete understanding of dropdown selection using 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 *