How To

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 🙂

Nachiket Panchal

Founder & Administrator of `errorsea` Having interest in Programming & Technology.

Recent Posts

5 Important Things To Know About WordPress Before You Use It

There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…

3 years ago

How to Install MySQL on Your PC in 3 Easy Steps

In this tutorial, I'm going to show you how to install MySQL on your computer.…

5 years ago

Download and Install Turbo C++ for Windows 10 (Full Installation Guide)

Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…

5 years ago

PHP .HTACCESS Redirects

We can redirect any webpage to any other or redirect the whole domain or website…

5 years ago

PHP Redirect Pages

There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…

5 years ago

PHP Include & Required

Include files in PHP are used in appending various global or config files. We can…

5 years ago