JSFiddle - React, Tailwind, and code Playground

by Sven Roeterdink

HTML

<body>

<div class="intro">
    <h1>Welcome to my JavaScript Quiz</h1>
    <h5>JSISSEXY tutorial</h5>
    <br>

    <span id="questions"></span>


        <form name="radioAnswers" id="ri">
            <input type="radio" id="answer0" name="choice" value="0"><label for ="answer0" id="a0">Answer A</label>
            <input type="radio" id="answer1" name="choice" value="1"><label for ="answer1" id="a1">Answer B</label>
            <input type="radio" id="answer2" name="choice" value="2"><label for ="answer2" id="a2">Answer C</label>
            <input type="radio" id="answer3" name="choice" value="3"><label for ="answer3" id="a3">Answer D</label>
        </form>

        <button id ="next" onclick=checkAnswers()>Submit answer</button>


</div>

</body>
</html>

CSS

.intro {
    padding-top: 10px;
    padding-left: 20px;
}

#next {
    padding-top: 20px;
}

#questions {
    font-size: 39px;
}

JavaScript

//global variable that takes the score and number
var totalScore = 0;
var numAnswer = 0;


//an array with objects that hold the questions
var allQuestions = [{question: ["Q1: Who is Prime Minister of the United Kingdom?"],
                    choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
                    correctAnswer:1},
    {question: ["Q2: When did Columbus found America?"],
     choices: ["1492", "1200", "0", "1493"],
    correctAnswer:0},
    {question: ["Q3: What is the Capital of Holland?"],
    choices: ["The Hague", "Amsterdam", "Rotterdam", "Utrecht"],
    correctAnswer:1},
    {question: ["Q4: How many centimeters are there in a meter?"],
    choices: ["30", "40", "50", "100"],
    correctAnswer:3},
    {question: ["Q5: How many universities does Amsterdam have?"],
    choices: ["1", "2", "3", "6"],
    correctAnswer:1}];

//create the questions created by the array
function createQuestions() {
    // first unselect all radiobuttons
    for (var i = 0; i<4; i++) {
        document.getElementById("answer" + i).checked = false;
    }
    var quizQuestion = document.getElementById("questions");
    quizQuestion.innerHTML = allQuestions[this.numAnswer].question[0];
    createOptions();
}

//change the innerHTML of the label by calling it's ID
function createOptions() {
    for (var o = 0; o <= allQuestions[0].choices[o].length; o++) {
        document.getElementById("a" + o).innerHTML = allQuestions[this.numAnswer].choices[o];
    }
}

//create an HTMLcollection using document.forms and check selected radiobutton and
//corresponding value.
function checkAnswers() {
    var methods = document.forms.radioAnswers.elements.choice;
    var answer = "error";

    if (this.numAnswer<4) {
        for (var i = 0; i<methods.length; i++) {
            if (methods[i].checked) {
                answer = methods[i].value;
                break;
            }
        }
        //check if answer is correct answer.
        if...