JSFiddle - React, Tailwind, and code Playground
by alxers
HTML
<div id="wrapper">
<h3 id="questionHeader"></h3>
<form id="quizForm">
<br>
<input type="radio" name="choice" value="0" id="choice1">
<label id="answ1" for="choice1"></label>
<br>
<input type="radio" name="choice" value="1" id="choice2">
<label id="answ2" for="choice2"></label>
<br>
<input type="radio" name="choice" value="2" id="choice3">
<label id="answ3" for="choice3"></label>
<br>
<button id="back" type="button">Back</button>
<button id="next" type="button">Next</button>
<p id="allQuestionNum"></p>
</form>
</div>
CSS
body {
margin: 0;
border-top: 10px solid #606060;
}
div {
margin: 0 auto;
width: 600px;
}
h3 {
margin-top: 20px;
font-size: 22px;
height: 40px;
color: #404040;
}
label {
color: #505050;
}
button {
border: 0;
padding: 5px;
margin: 15px 5px;
font-size: 14px;
background: #606060;
color: #FFFFFF;
}
JavaScript
var allQuestions = [{
question: "Which company first implemented the JavaScript language?",
choices: ["Microsoft", "Sun Microsystems", "Netscape Communications"],
correctAnswer: 2
}, {
question: "Which of the following browsers was the first to support JavaScript?",
choices: ["Microsoft Internet Explorer", "Netscape Navigator", "Opera"],
correctAnswer: 1
}, {
question: "The JavaScript international standard is called",
choices: ["ECMA-262 Standard", "JavaScript 1.3 Standard", "IEEE-262 Standard"],
correctAnswer: 0
}];
//
var questionCount = 0;
var score = 0;
// remember user answers
var answers = [];
// Set header and answer choices dynamically
function setHeader(questionNum) {
var questionHeaderEl = document.getElementById("questionHeader");
questionHeaderEl.innerHTML = allQuestions[questionNum].question;
}
function setAnswer(idEl, questionNum, choiceNum) {
var choiceEl = document.getElementById(idEl);
choiceEl.innerHTML = allQuestions[questionNum].choices[choiceNum];
}
//
function showQuestion() {
if (questionCount <= allQuestions.length - 1) {
setHeader(questionCount);
setAnswer("answ1", questionCount, 0);
setAnswer("answ2", questionCount, 1);
setAnswer("answ3", questionCount, 2);
}
}
function updateScore() {
for (var i = 0; i < allQuestions.length; i++) {
// use double equal to convert answers value to integer
if (allQuestions[i].correctAnswer == answers[i].value) {
score++;
}
}
}
function showScore() {
if (questionCount === allQuestions.length) {
updateScore();
document.getElementById("questionHeader").innerHTML = "Your score is " + score;
document.getElementById("quizForm").innerHTML = "<button id='start'>Start Quiz</button>";
var startButton = document.getElementById("start");
nextButton.addEventListener("click", showQuestion, false);
}
}
// select radiobutton...