JSFiddle - React, Tailwind, and code Playground

by jeanpierreb

HTML

<div class="container text-center">
        <div id="quiz">
            <h3 id="question"></h3>
            <ul id="choices">
            </ul>
            <button id="previous">previous</button>
            <button id="next">next</button>
        </div>
    </div>

JavaScript

var quizQuestions =
    [{
        question: "1. Who is Prime Minister of the United Kingdom?",
        choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
        correctAnswer:0
    },
    {
        question: "2. Who is Prime Minister of the United Kingdom?",
        choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
        correctAnswer:2
    },
    {
        question: "3. Who is Prime Minister of the United Kingdom?",
        choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
        correctAnswer:1
    }];

$(document).ready(function(){
        var all = quizQuestions,
            q = $("#question"),
            c = $("#choices"),
            ans = [],
            answerKey = [],
            current = 0;

        display(current);

        function display (id) {
            var question = all[id].question;
            var choices = all[id].choices;

            q.html(question);
            c.html(function(){
                var output = "<form>";
                for (var i = 0; i < choices.length; i++) {
                    output += "<input type='radio' name='question" +id
                    + "' value='" + choices[i] + "'> "
                    + choices[i] + "<br>";
                };
                output += "</form>"
                // console.log(output);
                return output;
            });
        };

        function changeDisplay (dir) {
            if (dir == 'next' && current < all.length-1) current++;
            if (dir == 'prev' && current > 0) current--;
            display(current);
        }

        function answerQ (q, a) {
            ans[q] = a;
            console.log(ans);
        }

        $(":radio").change(function(){
            answerQ( $(this)[0].name, $(this).val() );
        });

        $("#previous").click(function (){ changeDisplay('prev'); });
        $("#next").click(function (){ changeDisplay('next'); });

       ...