如何使用JavaScript预先选择select列表项?

要使用JavaScript预选择<select>列表项,请使用selectedIndex属性。添加要为此属性选择的内容的索引。

此处,在<script>标记下,add_select_id是<select>标记的ID,而add_item_index是数字索引。该索引是列表项索引,您需要添加要预选的项。

示例

您可以尝试运行以下代码以使用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>