[英]Get value of selected radio button
我正在尝试进行一个小的Javascript测验,而我试图使其运行的方法是检查单选按钮元素中的值是否与object属性(标记为correctAnswer)中的值匹配。
var allQuestions = [{
question: ["Question1?", "Question2?", "Question3"],
choices: [["choice1-1", "choice1-2", "choice1-3", "choice1-4"], ["choice2-1", "choice2-2", "choice2-3", "choice2-4"], ["choice3-1", "choice3-2", "choice3-3", "choice3-4"]],
correctAnswer: ["choice 1-4", "choice2-3", "choice3-2"]}];
var questions = document.getElementById('question');
var button = document.getElementById('next');
var radio = document.getElementsByName('buttons');
var a = document.getElementById('a');
var b = document.getElementById('b');
var c = document.getElementById('c');
var d = document.getElementById('d');
var labels = document.getElementsByName('labels');
for(var j=0; j < radio.length; j++) {
radio[j].value = allQuestions[0].choices[0][j];
}
for (var k=0; k < radio.length; k++) {
labels[k].innerHTML = allQuestions[0].choices[0][k];
}
var score = 0;
questions.innerHTML = allQuestions[0].question[0];
var i = 0;
var correct = allQuestions[0].correctAnswer[i];
button.onclick = function() {
if (i < allQuestions[0].question.length) {
i++;
if(radio.sel)
for(var l=0; l < radio.length; l++) {
questions.innerHTML = allQuestions[0].question[i]; //sets the question at top of page
radio[l].value = allQuestions[0].choices[i][l]; //sets value of each radio button.
//labels[l].innerHTML = allQuestions[0].choices[i][l]; //sets options for each question
a.innerHTML = allQuestions[0].choices[i][0];
b.innerHTML = allQuestions[0].choices[i][1];
c.innerHTML = allQuestions[0].choices[i][2];
d.innerHTML = allQuestions[0].choices[i][3];
}
}
我认为要将所选单选按钮的值与问题的正确答案相匹配,它应读取类似于以下内容的内容:
if(radio.checked.value == allQuestions[0].correctAnswer[i]) {
score++;
}
但是,当我将其放在函数顶部时,这特别不起作用。 有什么建议吗?
radio.checked返回一个布尔值,告诉您是否选中了该收音机,您无法将其与值链接。
正确的方法是遍历具有相同名称的所有无线电并获取已检查的无线电的值:
value = '';
for( i in radio ) {
if ( radio[i].checked )
value = radio[i].value;
}
您必须根据需要进行修改
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.