JSFiddle - React, Tailwind, and code Playground
HTML
<body onload="init()">
<h1>Javascript Quiz Application</h1>
<div id="question"></div>
<form id="answers" name="answers"></form>
<div id="actions">
<button id="next" onclick="showNextQuestion()">Next</button>
</div>
<div id="result"></div>
</body>
JavaScript
var allQuestions = [
{
question: "3*5",
choices: ["1.5", "15", "12", "21"],
correctAnswer: 1
},
{
question: "5+3",
choices: ["15", "7", "1", "8"],
correctAnswer: 3
},
{
question: "5-3",
choices: ["2", "7", "16", "1.9"],
correctAnswer: 0
},
{
question: "5/2",
choices: ["3", "2.6", "2.5", "9"],
correctAnswer: 2
}
];
var currentQuestionIndex = 0;
var results = [];
function init() {
currentQuestionIndex = 0;
results = [];
showQuestion();
}
function showQuestion() {
var questionObj = allQuestions[currentQuestionIndex];
document.getElementById("question").innerHTML = questionObj.question;
var radios = "";
for(var i=0; i<questionObj.choices.length; ++i) {
radios += "<input type='radio' name='answer' value='" +i +"' />" +questionObj.choices[i];
}
document.getElementById("answers").innerHTML = radios;
}
function checkAnswer() {
var questionObj = allQuestions[currentQuestionIndex];
var shouldBe = questionObj.correctAnswer;
var selected = -1;
for(var i=0; i<questionObj.choices.length; ++i) {
if(document.answers.answer[i].checked) {
selected = i;
break;
}
}
results[currentQuestionIndex] = shouldBe == selected;
}
function showNextQuestion() {
checkAnswer();
++currentQuestionIndex;
if(currentQuestionIndex == allQuestions.length) {
showResult();
} else {
showQuestion();
}
}
function showResult() {
document.getElementById("question").innerHTML = "";
document.getElementById("answers").innerHTML = "";
document.getElementById("actions").innerHTML = "";
var msg = "<h2>Results</h2>";
var correctCount = 0;
for(var i=0; i<results.length; ++i) {
if(results[i]) {
++correctCount;
}
msg += "Question " +i +" " +results[i] + "<br>";
}
var...