JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<div id="main">
<h1>My Dynamic Quiz</h1>
<div id="question"></div>
<form id="choices" name="choices"></form>
<button>Next</button>
<div id="results"></div>
</div>
</body>
CSS
body {
background-color:#f0f0f0;
}
div#main {
margin: 50px auto;
background-color:#66CCFF;
width:500px;
height:100%;
border: #000 5px solid;
}
h1, h2, h3, p, form {
color:#fff;
font-family:arial, helvetica, sans-serif;
margin: 10px;
padding:5px;
}
input {
margin:8px 4px 8px 8px;
}
button {
background-color:#000;
color:#fff;
cursor:pointer;
}
JavaScript
var allQuestions = [{
question: "5 x 5 = ?",
choices: ["25", "9", "18", "19"],
correctAnswer: 0
}, {
question: "5 x 10 = ?",
choices: ["5", "9", "18", "50"],
correctAnswer: 3
}, {
question: "5 x 3 = ?",
choices: ["2", "9", "15", "9"],
correctAnswer: 2
}, {
question: "2 x 5 = ?",
choices: ["1", "10", "18", "7"],
correctAnswer: 1
}];
$("document").ready(function loaderSet() {
currentIndexQuestion = 0;
showQuestion();
answerScore = 0;
});
var currentIndexQuestion = 0;
var answerScore = 0;
function showQuestion() {
var questionObj = allQuestions[currentIndexQuestion];
$("#question").html("<p>" + questionObj.question + "</p>");
var radios = "";
for (var i = 0; i < questionObj.choices.length; i++) {
radios += "<input type='radio' name='choices' value='" + i + "' />" + questionObj.choices[i];
}
$("#choices").html(radios);
}
function checkQuestions() {
var questionObj = allQuestions[currentIndexQuestion];
var answer = $("input:radio[name=choices]:checked").val();
if (answer == questionObj.correctAnswer) {
answerScore++;
}
}
function showResult() {
$("button, #question, #choices").hide();
$("#results").html("<p>You scored " + answerScore + " out of a possible 4.</p>");
}
$("button").on('click', function showNextQuestion() {
checkQuestions();
++currentIndexQuestion;
if (currentIndexQuestion == allQuestions.length) {
showResult();
} else {
showQuestion();
}
});