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

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

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


当前回答

要使用PHP和JavaScript设置默认值:

State: <select id="State">
<option value="" selected disabled hidden></option>
<option value="Andhra Pradesh">Andhra Pradesh</option>
<option value="Andaman and Nicobar Islands">Andaman and Nicobar Islands</option>
.
.
<option value="West Bengal">West Bengal</option>
</select>
<?php
if(isset($_GET['State'])){
    echo <<<heredoc
<script>
document.getElementById("State").querySelector('option[value="{$_GET['State']}"]').selected = true;
</script>
heredoc;
}
?>

其他回答

要使用PHP和JavaScript设置默认值:

State: <select id="State">
<option value="" selected disabled hidden></option>
<option value="Andhra Pradesh">Andhra Pradesh</option>
<option value="Andaman and Nicobar Islands">Andaman and Nicobar Islands</option>
.
.
<option value="West Bengal">West Bengal</option>
</select>
<?php
if(isset($_GET['State'])){
    echo <<<heredoc
<script>
document.getElementById("State").querySelector('option[value="{$_GET['State']}"]').selected = true;
</script>
heredoc;
}
?>

另一个例子;使用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);

我使用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";

我更喜欢这样:

<select>
   <option selected hidden>Choose here</option>
   <option value="1">One</option>
   <option value="2">Two</option>
   <option value="3">Three</option>
   <option value="4">Four</option>
   <option value="5">Five</option>
</select>

选择选项后,“选择此处”消失。

每个选项中都需要一个“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