[英]How can I set a select element's itemindex to -1?
我正在將動態值添加到View代碼中的select元素中,就像在View / .cshtml中一樣:
@model WebAppRptScheduler.Models.HomeModel
@using System.Data
@{
DataTable dtUnits = Model.Units as DataTable;
var units = from x in dtUnits.AsEnumerable()
select new
{
unit = x.Field<string>("unit")
};
.....
<select class="form-control, dropdown" name="unitsselect">
@foreach (var field in units)
{
<option id="selItem_@(field.unit)" value="@field.unit">@field.unit</option>
}
</select>
.....
這些值可以很好地填充,但是會自動選擇select元素中的第一個選項。 如何將其設置為-1,以便什么都沒有選擇? 我可以在上述foreach循環之后執行此操作,還是必須使用javascript來執行?還是可以在C#代碼隱藏文件中執行?
您可以在foreach之外添加默認選項:
<select class="form-control, dropdown" name="unitsselect">
//_________________________^ Remove this comma
<option value="0" selected>Choose unit please</option>
@foreach (var field in units)
{
<option id="selItem_@(field.unit)" value="@field.unit">@field.unit</option>
}
</select>
像這樣 :
<select class="form-control, dropdown" name="unitsselect">
<option disabled selected value> -- select an option -- </option>
@foreach (var field in units)
{
<option id="selItem_@(field.unit)" value="@field.unit">@field.unit</option>
}
</select>
-- select an option --
將默認顯示。 但是,如果您選擇一個選項,則將無法選擇它
來源: 默認選擇選項為空白
如果您不喜歡<select>中的虛擬/空元素。 您可以在腳本部分添加一行JavaScript,並將ID設置為<select id =“ unitselect” ...>元素
@section scripts
{
<script type="text/javascript">
document.getElementById("unitselect").selectedIndex = -1;
...
我認為您必須在開始時在集合中添加空值,以便它將被選中,或者您可以在循環之前執行此操作
<option value="0">Please select</option>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.