How to preselect Dropdown Using JavaScript Programmatically?

JavascriptWeb DevelopmentFront End Scripts

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.

Example

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

Live Demo

<!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>
raja
Published on 07-Feb-2018 08:23:19
Advertisements