I'm working on a quiz app, but I can't seem to get the value or the index of the radio buttons on the page.
Here's my code:
HTML:
<div id="container">
<div id="quiz"></div>
<div id="choices"></div>
<input id="next" type="button" value="Next">
<input id="back" type="button" value ="Back">
<div id="results"></div>
</div>
JavaScript:
var allQuestions = [
{
question: "Who is the best in the world?",
choices: ["CM Punk", "John Cena", "Daniel Bryan", "Roman Reigns"],
correctAnswer: 0
},
{
question: "Who is the current WWE World Champion?",
choices: ["John Cena", "Brock Lesnar", "Triple H"],
correctAnswer: 1
},
{
question: "Where is Toronto located?",
choices: ["Ontario", "California", "Georgia", "Texas"],
correctAnswer: 0
},
{
question: "What is the largest California city?",
choices: ["Los Angeles", "San Fransico", "San Deigo", "Anahiem"],
correctAnswer: 0
}
];
var quiz = document.getElementById('quiz');
var choicesContainer = document.getElementById('choices');
var nextButton = document.getElementById('next');
var backButton = document.getElementById('back');
var score = 0;
var questionIndex = 0;
// A function to show the question.
function showQuiz() {
var currentQuestion = allQuestions[questionIndex].question;
quiz.textContent = currentQuestion;
choicesContainer.innerHTML = "";
var choicesNum = allQuestions[questionIndex].choices.length;
for (var i = 0; i < choicesNum; i++) {
var choice = allQuestions[questionIndex].choices[i];
choicesHTML = "<input type='radio' name='choice'>" + choice + "</br>";
choicesContainer.innerHTML += choicesHTML;
}
}
function checkScore() {
//var correctAnswers = allQuestions[questionIndex].correctAnswer;
var radios = document.querySelectorAll('[type=radio]');
var userAnswers;
for (var i = 0; i < radios.length; i++) {
if(radios[i].checked) {
userAnswers = radios[i].value;
console.log(userAnswers);
}
}
}
showQuiz();
nextButton.addEventListener('click', function(){
questionIndex++;
showQuiz();
checkScore();
});
backButton.addEventListener('click', function(){
questionIndex--;
showQuiz();
});
First, I thought it was because I was calling the checkAnswers() function before the DOM was ready, but that doesn't seem the be the case so I'm stuck.
Any help, would be awesome and greatly appreciated. Thanks!