JSFiddle - React, Tailwind, and code Playground
by LtDarien
HTML
<body>
<form id="quiz">
<p id="question"></p>
<ul id="choices"></ul>
</form>
<button id="start" form="quiz">Start</button>
</body>
CSS
ul {list-style: none;}
JavaScript
var questions = [
{question: "What is 1 + 1?", choices: ["1","2","3","4"], correctAnswer: "2"},
{question: "What is 2 + 2?", choices: ["1","2","3","4"], correctAnswer: "4"},
{question: "What is 3 + 3?", choices: ["6","2","3","4"], correctAnswer: "1"},
{question: "What is 4 + 4?", choices: ["1","8","3","4"], correctAnswer: "2"},
{question: "What is 5 + 5?", choices: ["1","2","10","4"], correctAnswer: "3"},
{question: "What is 6 + 6?", choices: ["1","2","3","12","5","6","8"], correctAnswer: "4"},
];
var questionIndex = 0;
var score = 0;
function setupQuiz() {
}
function loadQuestion(index){
$('#quiz').append('<p id="question"></p>').append('<ul id="choices"></ul>');
$('#question').text('Question '+ (index+1) + ': ' + questions[index].question);
for (var x = 0; x < questions[index].choices.length; x++) {
$('ul').append('<li></li>');
$('li').last().attr('id', 'choice' + (x+1))
.append('<input type="radio" name="choices" id="' + (x+1) + '">')
.append('<span>' + questions[index].choices[x] + '</span>');
}
}
$(document).ready(function() {
$('button').on("click", function() {
if ($(this).attr('id') == 'start') {
$(this).text("Next");
$(this).attr("id", "next");
loadQuestion(questionIndex);
return false;
}
else {
if(!$('input:radio[name="choices"]').is(':checked')) {
alert('Make a selection');
return false;
}
if ($(':checked').attr('id') == questions[questionIndex].correctAnswer){
alert("Correct! Your score is: " + ++score + ".");
} else {
alert("Wrong! Your score is: " + score + ".");
}
$('#quiz').empty();
if (++questionIndex < questions.length) {
loadQuestion(questionIndex);
} else {
$('button').remove();
$('#quiz').append('<p>Quiz over! Your score was ' + score + ' out of ' + questions.length + '.');
}
return false;
}
});
});