我认为在下面的<select>元素上添加一个“value”属性集会导致默认选择包含我提供的“value”的<option>:
<select name=“hall”id=“hall”value=“3”><option>1</option><option>2</option><option>3</option><选项>4</选项><选项>5</选项></选择>
然而,这并没有像我预期的那样奏效。我如何设置默认选择哪个<option>元素?
我认为在下面的<select>元素上添加一个“value”属性集会导致默认选择包含我提供的“value”的<option>:
<select name=“hall”id=“hall”value=“3”><option>1</option><option>2</option><option>3</option><选项>4</选项><选项>5</选项></选择>
然而,这并没有像我预期的那样奏效。我如何设置默认选择哪个<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);
其他回答
另一个例子;使用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);
缺少标记的value属性,因此它不会显示为所需的选定项。默认情况下,如果在标签上设置了value属性,则在下拉页面加载时显示第一个选项。。。。我这样解决了我的问题
每个选项中都需要一个“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
我就是这样做的。。。
<form action="../<SamePage>/" method="post">
<?php
if ( $_POST['drop_down'] == "")
{
$selected = "";
}
else
{
$selected = "selected";
}
?>
<select name="select" size="1">
<option value="1" <?php $selected ?>>One</option>
//////// OR ////////
<option value="2" $selected>Two</option>
</select>
</form>
我使用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";