I'm writing a form for a personality test. The page has questions where the user would need to choose an answer for each. The page will not allow the user to skip questions and it will alert them to answer the missing questions. When the form is submitted, the page will show the score.
I'm trying to store the values of radio buttons in an array using a for loop. It is not working.
Here is the HTML code:
<!-- Form -->
<form name="quiz" onsubmit="return show()">
<!-- Question 1 -->
<p>Question 1</p>
<input type="radio" name="q0" value="a"> a
<br>
<input type="radio" name="q0" value="b"> b
<br>
<input type="radio" name="q0" value="c"> c
<!-- Question 2 -->
<!-- Question 3 -->
<!-- Question 4 -->
<!-- Question 5 -->
<p>Question 5</p>
<input type="radio" name="q4" value="a"> a
<br>
<input type="radio" name="q4" value="b"> b
<br>
<input type="radio" name="q4" value="c"> c
<!-- Submit Button -->
<input type="submit" value="Show Result">
</form>
Here is my JavaScript code:
function show() {
var questions = 5;
var score = 0;
var solution = ["a", "c", "a", "b", "b"];
var answers = [];
for (i = 0; i < questions; i++) {
answers[i] = document.quiz.eval('q' + i).value;
if (answers[i] == null || answers[i] == '') {
window.alert("You need to answer question " + (i + 1));
return false;
}
if (solution[i] == answers[i]) {
score++;
}
}
window.alert(score);
}