JSFiddle - React, Tailwind, and code Playground
by Nicole Phillips
HTML
<h3></h3>
<form>
<input type="radio" name="answer" value="0" /><span></span>
<input type="radio" name="answer" value="1" /><span></span>
<input type="radio" name="answer" value="2" /><span></span>
<input type="radio" name="answer" value="3" /><span></span>
<br />
<input type="button" name="next" value="Next Question >" id="next" />
</form>
JavaScript
// array to store all questions, choices, correct answer
var allQuestions = [
{
question: "Who is the Prime Minister of the United Kingdom?",
choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
correctAnswer: 0
}, {
question: "Who is Batman?",
choices: ["Clark Kent", "Bruce Wayne", "Dick Grayson", "Commissioner Gordon"],
correctAnswer: 1
}, {
question: "Who is Magneto's daughter?",
choices: ["Rogue", "Emma Frost", "Scarlet Witch", "Phoenix"],
correctAnswer: 2
}
];
var questNum = 0, // index
score = 0, // score
question = null, // current question
nextQuestion = function(){
// get question at current index
question = allQuestions[ questNum ];
questNum++; // increment index
if(question){ // if question exists, display it
// populate h3 text with question
$('h3').text(question.question);
// loop through all radio buttons and populate them
$('input[name="answer"]').each(function(i, el){
$(el).attr('checked', false).
next('span').text( question.choices[i] );
});
} else { // no more questions! game over. hide form. display score.
$("form").hide();
$("h3").text("Game over! Your score is " + score + "/" + allQuestions.length+ ".");
}
},
checkAnswer = function(){
var selectedAnswer = $('input:radio[name="answer"]:checked');
if( selectedAnswer.length == 0 ){
alert('You must select an answer!');
} else {
if( selectedAnswer.val() == question.correctAnswer){
score++;
}
nextQuestion();
}
};
$(document).ready(function(){
$('#next').on('click', checkAnswer);
nextQuestion();
});