使用javascript选择单选按钮。

时间:2014-02-04 10:13:35

标签: javascript html

我目前正在学习javascript。我想创建一个动态测验,现在我想检查我的radiobuttons的值。这是我的代码:

HTML:

<div class="intro">
<h1>Welcome at my JavaScript Quiz</h1>
<br>

<span id="questions"></span>

<form name="radioAnswers">
    <input type="radio" id="answer0" name="choice" value="a"><label for ="answer0" id="a0">Answer A</label>
    <input type="radio" id="answer1" name="choice" value="b"><label for ="answer1" id="a1">Answer B</label>
    <input type="radio" id="answer2" name="choice" value="c"><label for ="answer2" id="a2">Answer C</label>
    <input type="radio" id="answer3" name="choice" value="c"><label for ="answer3" id="a3">Answer D</label>
</form>

<div class="buttons">
<button onclick="checkAnswers()">Submit answer</button>
</div>

checkAnswers函数检查答案。根据我的理解,document.forms.radioAnswers.elements.choice将创建一个HTMLcollection。我想迭代这个arraylike列表,并希望查看哪个被检查,然后将其放入answer变量中。像这样:

function checkAnswers() {
    var methods = document.forms.radioAnswers.elements.choice;
    var answer;
    for (var i = 0; i<methods.length; i++) {
        if (methods[i].checked) {
            answer = methods[i].value;
        } else {
            answer = "error"
        }
    } alert(answer);
}

当我运行它时会发出警告&#34;错误&#34;每时每刻。我错过了什么?

2 个答案:

答案 0 :(得分:2)

当你找到答案时,你需要打破循环,如下所示:

function checkAnswers() {
   var methods = document.forms.radioAnswers.elements.choice;
    var answer = "error";
    for (var i = 0; i<methods.length; i++) {
        if (methods[i].checked) {
            answer = methods[i].value;
            break;
        }
    }
    alert(answer);
}

DEMO

答案 1 :(得分:1)

试试这个:

function checkAnswers() {
   var answer="error";
    if (document.getElementById('answer0').checked) {
 answer = document.getElementById('answer0').value;
}
    if (document.getElementById('answer1').checked) {
 answer = document.getElementById('answer1').value;
}
    if (document.getElementById('answer2').checked) {
 answer = document.getElementById('answer2').value;
}
    if (document.getElementById('answer3').checked) {
 answer = document.getElementById('answer3').value;
}
    alert(answer);
}

DEMO