Computer >> Computer tutorials >  >> Programming >> Javascript

How to preselect Dropdown Using JavaScript Programmatically?


To preselect a dropdown item using JavaScript, use the selectedIndex property. Add an index of what item you want to be selected.

Dropdown item list is created in HTML using the <select> tag. For JavaScript, we use the <script> tag. Here, under the <script> tag, add_select_id is the id of the <select> tag, whereas add_item_index is the index in numbers. This index is the list item index; you need to add for the item you want to be preselected.

How to preselect Dropdown Using JavaScript Programmatically?

Example

You can try to run the following code to preselect dropdown using JavaScript programmatically −

<!DOCTYPE html>
<html>
   <head>
      <title>HTML select tag</title>
   </head>
   <body>
      <p> Select any one:</p>
      <form>
         <select id="dropdown" name="dropdown" class="form-control">
            <option value = "Android">Android</option>
            <option value = "CSS">CSS</option>
            <option value = "Python">Python</option>
         </select>
      </form>
      <script>
         document.getElementById("dropdown").selectedIndex = "1";
      </script>
   </body>
</html>