In this article, we are going to learn how to set selected value of dropdown in JavaScript for dynamic dropdown selection on HTML webpage.
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> Read Also: HTML Interview Questions and Answers
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 🙂
There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…
In this tutorial, I'm going to show you how to install MySQL on your computer.…
Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…
We can redirect any webpage to any other or redirect the whole domain or website…
There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…
Include files in PHP are used in appending various global or config files. We can…