-
Add answer
array
to store the answersvar answers = [];
-
update the answers’s value when clicked button, let correct to be calculated at last.
function checkAnswer() {
choice = document.getElementsByName("answerChoice"); var checkedAnswer = null; for (var i = 0; i < choice.length; i++) { if(choice[i].checked) { answers[pos] = choice[i].value; } } if( answers[pos] == null ) { document.getElementById("error").innerHTML = 'Please select an answer' return false; } pos++ renderQuestions()
}
-
Alter the input after render is complete to set check to radio
if (typeof answers[pos] !== undefined) { var radios = document.getElementsByName('answerChoice'); var rLen = radios.length, i; for (i = 0; i < rLen; ++i) { if (answers[pos] === radios[i].value) { radios[i].checked = true; } } }
-
calculate result on output
if(pos >= allQuestions.length) { // Check answers var qLen = allQuestions.length, correct = 0; for (var i = 0; i < qLen; ++i) { if (answers[i] === allQuestions[i].answer) { ++correct; } } testStatus.innerHTML = "Test Completed"; test.innerHTML = "<h2>" + "You got " + correct + " out of " + allQuestions.length + "</h2><br/>"; pos = 0; return false };
With worked jsFiddle
0
solved How to keep the previous answer selected? (javascript quiz) [closed]