使用 JavaScript 从下拉列表中获取选定的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18846821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Selected value from dropdown using JavaScript
提问by craig
I have the following HTML
我有以下 HTML
<form>
<div class="answer1wrap">
<select id="mySelect">
<option value="void">Choose your answer</option>
<option value="To measure time">To measure time</option>
<option value="To measure distance">To measure distance</option>
<option value="To measure volume">To measure volume</option>
</select>
</div>
</form>
<button class="btn btn-default" id="checkbtn" onclick="answers();" type="button"><span class="glyphicon glyphicon-check"></span> Check answers</button>
I also have the javascript
我也有 javascript
function answers()
{
var selectedanswer=document.getElementById("mySelect").selectedIndex;
if (document.getElementsByTagName("option")[selectedanswer].value=="To measure time");{
alert("Thats correct");
}
}
I was hoping that when the button is pressed, it would check to see if the 'to measure time' option was selected and alert me ONLY if that was selected. However no matter which option has been selected it always shows the alert.
我希望当按下按钮时,它会检查是否选择了“测量时间”选项,并仅在选择时提醒我。但是,无论选择了哪个选项,它始终会显示警报。
Any ideas?
有任何想法吗?
回答by cocco
Maybe it's the comma in your if
condition.
也许这是您的if
条件中的逗号。
function answers() {
var answer=document.getElementById("mySelect");
if(answer[answer.selectedIndex].value == "To measure time.") {
alert("That's correct!");
}
}
You can also write it like this.
你也可以这样写。
function answers(){
document.getElementById("mySelect").value!="To measure time."||(alert('That's correct!'))
}
回答by Wez
The first thing i noticed is that you have a semi colon just after your closing bracket for your if statement );
我注意到的第一件事是在 if 语句的右括号后面有一个分号 );
You should also try and clean up your if statement by declaring a variable for the answer separately.
您还应该尝试通过分别为答案声明一个变量来清理 if 语句。
function answers() {
var select = document.getElementById("mySelect");
var answer = select.options[select.selectedIndex].value;
if(answer == "To measure time"){
alert("Thats correct");
}
}
回答by Derk Arts
Try
尝试
var e = document.getElementById("mySelect");
var selectedOp = e.options[e.selectedIndex].text;
回答by bitoiu
Working jsbin: http://jsbin.com/ANAYeDU/4/edit
工作jsbin:http://jsbin.com/ANAYeDU/4/edit
Main bit:
主要位:
function answers()
{
var element = document.getElementById("mySelect");
var elementValue = element.value;
if(elementValue == "To measure time"){
alert("Thats correct");
}
}