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

How to preselect a <select> list item using JavaScript?


To preselect a <select> list item using JavaScript, use the selectedIndex property. Add an index of what you want to be selected for this property.

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 a <select> list item using JavaScript?

Example

You can try to run the following code to preselect a list item using JavaScript −

<!DOCTYPE html>
<html>
   <head>
      <title>Preselect List Item</title>
   </head>
   <body>
      <p> Select any one:</p>
      <form>
         <select id="dropdown" name="dropdown" class="form-control">
            <option value = "Java">Java</option>
            <option value = "Discrete Mathematics">Discrete Mathematics</option>
            <option value = "Digital Electronics">Digital Electronics</option>
         </select>
      </form>
      <script>
         document.getElementById("dropdown").selectedIndex = "2";
      </script>
   </body>
</html>