我认为在下面的<select>元素上添加一个“value”属性集会导致默认选择包含我提供的“value”的<option>:

<select name=“hall”id=“hall”value=“3”><option>1</option><option>2</option><option>3</option><选项>4</选项><选项>5</选项></选择>

然而,这并没有像我预期的那样奏效。我如何设置默认选择哪个<option>元素?


当前回答

为要作为默认选项的选项设置selected=“selected”。

<option selected="selected">
3
</option>

其他回答

每个选项中都需要一个“id”属性,此解决方案才能正常工作:

<脚本>函数select_option(id,value_selected){var选择;select=document.getElementById(id);如果(select==null)返回0;var选项;option=select.options.namedItem(value_selected);if(option==null)返回0;option.selected=“已选择”;返回true;} </script><select name=“hall”id=“hall”><option id=“1”>1</option><option id=“2”>2</option><option id=“3”>3</option><option id=“4”>4</option><option id=“5”>5</option></选择><script>select_option(“大厅”,“3”)</脚本>

函数首先尝试查找id为的<select>,然后在<select>选项中搜索value_selected,如果找到它,则将所选属性设置为true。否则为False

我使用Angular,并通过以下方式设置默认选项

HTML模板

<select #selectConnection [(ngModel)]="selectedVal" class="form-control  col-sm-6 "  max-width="100px"   title="Select" 
      data-size="10"> 
        <option  >test1</option>
        <option >test2</option>      
      </select>

脚本:

sselectedVal:any="test1";

如果您想使用表单中的值并保持其动态,请尝试使用php

<form action="../<SamePage>/" method="post">


<?php
    $selected = $_POST['select'];
?>

<select name="select" size="1">

  <option <?php if($selected == '1'){echo("selected");}?>>1</option>
  <option <?php if($selected == '2'){echo("selected");}?>>2</option>

</select>
</form>

设置selected=“selected”,其中选项值为3

请参见下面的示例

<option selected="selected" value="3" >3</option>

另一个例子;使用JavaScript设置所选选项。

(您可以使用此示例将值数组循环到下拉组件中)

<select id=“yourDropDownElementId”><select/>

// Get the select element
var select = document.getElementById("yourDropDownElementId");
// Create a new option element
var el = document.createElement("option");
// Add our value to the option
el.textContent = "Example Value";
el.value = "Example Value";
// Set the option to selected
el.selected = true;
// Add the new option element to the select element
select.appendChild(el);