Quiz
by leighm
HTML
<div id="container" class="container">
<h2 id="question"></h2>
<div id="radioGroup"></div>
<button type="submit" class="btn btn-default" id="prev-question">Previous Question</button>
<button type="submit" class="btn btn-default" id="next-question">Next Question</button>
</div>
JavaScript
// this array holds each question, possible answers, and correct answer
let allQuestions = [
{
question: 'What colour is the sky?',
choices: ['Red', 'Green', 'Blue', 'Purple'],
correctAnswer: 2
},
{
question: 'What colour is the grass?',
choices: ['Purple', 'Green', 'Red', 'Blue'],
correctAnswer: 1
},
{
question: 'What colour is a banana?',
choices: ['Yellow', 'Green', 'Orange', 'Brown'],
correctAnswer: 0
}
];
// Global variables
let questionCounter = 0;
let totalQuestions = allQuestions.length;
let totalScore = 0;
let list = document.createElement('ul');
let nextButton = document.getElementById('next-question');
let prevButton = document.getElementById('prev-question');
prevButton.disabled = true;
let userAnswer = allQuestions[questionCounter].userAnswer;
let score = allQuestions[questionCounter].score;
// Quiz function
let quiz = function quiz() {
// holds the components (object) of a single question (question, choices, answer, score)
// using our counter variable
let singleQuestion = allQuestions[questionCounter];
// identify elements from the existing markup
let correctAnswer = singleQuestion.correctAnswer;
let radioGroup = document.getElementById('radioGroup');
let question = document.getElementById('question');
question.innerHTML = singleQuestion.question;
radioGroup.appendChild(list);
// loop through each choice and output html to display them
for(let i=0; i < singleQuestion.choices.length; i++) {
// inside the loop we need to create the html elements for each option
let item = document.createElement('li');
let optionButton = document.createElement('input');
let optionText = document.createTextNode(singleQuestion.choices[i]); // variable that will hold the choice text
optionButton.setAttribute('type', 'radio');
...