使用JavaScript从下拉列表中获取选定值

时间:2013-09-17 10:01:04

标签: javascript select drop-down-menu option

我有以下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>

我也有javascript

function answers()
{
  var selectedanswer=document.getElementById("mySelect").selectedIndex;

  if (document.getElementsByTagName("option")[selectedanswer].value=="To measure time");{
    alert("Thats correct"); 
  }
}

我希望当按下按钮时,它会检查是否选择了“测量时间”选项并仅在选中时提醒我。但无论选择哪个选项,它都会显示警报。

有什么想法吗?

4 个答案:

答案 0 :(得分:20)

也许这是您if条件中的逗号。

function answers() {
var answer=document.getElementById("mySelect");
 if(answer[answer.selectedIndex].value == "To measure time.") {
  alert("That's correct!"); 
 }
}

您也可以这样写。

function answers(){
 document.getElementById("mySelect").value!="To measure time."||(alert('That's correct!'))
}

答案 1 :(得分:5)

尝试

var e = document.getElementById("mySelect");
var selectedOp = e.options[e.selectedIndex].text;

答案 2 :(得分:5)

我注意到的第一件事就是你的if语句的结束括号后面有一个半冒号);

您还应该尝试通过单独声明答案的变量来清理您的if语句。

function answers() {

var select = document.getElementById("mySelect");
var answer = select.options[select.selectedIndex].value;

    if(answer == "To measure time"){
        alert("Thats correct"); 
    }

}

http://jsfiddle.net/zpdEp/

答案 3 :(得分:3)

工作jsbin:http://jsbin.com/ANAYeDU/4/edit

主要位:

function answers()
{

var element = document.getElementById("mySelect");
var elementValue = element.value;

if(elementValue == "To measure time"){
  alert("Thats correct"); 
  }
}