Francis Sunday Francis Sunday - 2 months ago 5
HTML Question

How to Return variables from an iteration

Good day all, i was creating this javascript quiz app and i have some bugs where i can't figure out.

it displays correctly, but where the error is, is at the output which is supposed to return "You answered (no of questions answered) out of (total number of questions). Here it just displays 0 if when the value is true.

Below is my script.
thanks



var pos = 0,
test, test_status, question, choice, choices, chA, chB, chC, correct = 0;
var questions = [
["What is 10 + 4?", "12", "14", "16", "B"],
["What is 10 + 5?", "15", "14", "16", "A"],
["What is 20 + 4?", "12", "24", "16", "B"],
["What is 30 + 4?", "32", "24", "34", "C"],
["What is 10 + 6?", "12", "14", "16", "C"]
];

function _(x) {
return document.getElementById(x);
}

function renderQuestion() {
test = _("test");
if (pos >= questions.length) {
test.innerHTML = "<h2>You got " + correct + " of " + questions.length + " Questions correct</h2>";
_("test_status").innerHTML = "Test Completed";
pos = 0;
correct = 0;
return false;
}
_("test_status").innerHTML = "Question " + (pos + 1) + " of " + questions.length;
question = questions[pos][0];
chA = questions[pos][1];
chB = questions[pos][2];
chC = questions[pos][3];
test.innerHTML = "<h3>" + question + "</h3>";
test.innerHTML += "<input type='radio' name='chioces' value='A'> " + chA + "<br>";
test.innerHTML += "<input type='radio' name='chioces' value='B'> " + chB + "<br>";
test.innerHTML += "<input type='radio' name='chioces' value='C'> " + chC + "<br>";
test.innerHTML += "<button onclick='checkAnswer()'>Submit Answer</button>";
}

function checkAnswer() {
choices = document.getElementsByName("choices");
for (var i = 0; i < choices.length; i++) {
if (choices[i].checked) {
choice = choices[i].value;
}
}
if (choice == questions[pos][4]) {
correct++;
}
pos++;
renderQuestion();
}
window.addEventListener("load", renderQuestion, false);

<div id="test_status"></div>
<div id="test"></div>




Answer

Simple debug statement

choices = document.getElementsByName("choices");
console.log(choices)

will show that it returns no elements.

Why!? Because you spelled choices wrong.

name='chioces'