【问题标题】:selected value from dropdown从下拉列表中选择的值
【发布时间】:2020-04-24 21:34:01
【问题描述】:
如何检查下拉html中选择了什么值?
实时(客户端)
<div>
<select id="myList" name="testList">
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
</select>
</div>
@{
if ***[if the value from dropdown = 1) ]?***
{
var variable = x;
}
}
【问题讨论】:
标签:
javascript
html
asp.net
razor
【解决方案1】:
这可能会有所帮助:Get selected value in dropdown list using JavaScript
但这里有一个例子:
getSelected();
function getSelected() {
let list = document.getElementById("myList");
let selected = list.options[list.selectedIndex].value;
let writeSelected = document.getElementById("selectedItem")
if (selected === "2") {
return writeSelected.innerHTML = "Best month"
}
writeSelected.innerHTML = selected
}
<div>
<select id="myList" onchange="getSelected()" name="testList">
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
</select>
</div>
<p>
Selected: <span id="selectedItem"></span>
</p>
【解决方案2】:
我写这个
<script>
var XXX = document.getElementsByName("testList");
var YYY = XXX.options[list_month.selectedIndex].value;
var nr_days = YYY;
</script>
但我对变量有疑问:nr_days ||沟通:nr_days 不存在
@for (int nr_rows = 0; nr_rows < nr_days; nr_rows++)
.cshtml
【解决方案3】:
您可以使用此代码检查选择的值。
/***This code is to get value of selected option****/
$("select#myList").change(function(){
var selectedMonth = $(this).children("option:selected").val();
alert("You have selected the month - " + selectedMonth);
});
/***This code is to get text of selected option****/
$("select#myList").change(function(){
var selectedMonth = $(this).children("option:selected").text();
alert("You have selected the month - " + selectedMonth);
});
【解决方案4】:
<html>
<head>
<script>
function demo()
{
var a=document.getElementById("txt").value;
document.write("selected month is"+a);
}
</script>
</head>
<body>
<div>
<select id="myList" name="testList" onchange="demo()" id="txt">
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
</select>
</div>
</body>
</html>
【讨论】:
-
请始终将您的答案放在上下文中,而不仅仅是粘贴代码。有关详细信息,请参阅here。