Skip to main content

Basic Mcq

<!DOCTYPE html>

<html>

<head>

    <title>Mock Test</Basic MCQ>

</head>

<body>

    <h1>Mock Test</h1>

    <form id="quiz-form">

        <div id="question-container">

            <div id="question"></div>

            <div id="options"></div>

        </div>

        <button id="next-button">Next</button>

    </form>


    <div id="result-container" style="display: none;">

        <h2>Quiz Completed!</h2>

        <p>Your Score: <span id="score"></span></p>

    </div>


    <script>

        const quizData = [

            {

                question: "What is the capital of France?",

                options: ["Paris", "London", "Berlin", "Rome"],

                answer: 0

            },

            {

                question: "Which planet is known as the 'Red Planet'?",

                options: ["Mars", "Earth", "Venus", "Jupiter"],

                answer: 0

            },

            // Add more questions here

        ];


        const quizForm = document.getElementById("quiz-form");

        const questionContainer = document.getElementById("question-container");

        const questionElement = document.getElementById("question");

        const optionsElement = document.getElementById("options");

        const nextButton = document.getElementById("next-button");

        const resultContainer = document.getElementById("result-container");

        const scoreElement = document.getElementById("score");


        let currentQuestion = 0;

        let score = 0;


        function showQuestion(question) {

            questionElement.innerText = question.question;

            optionsElement.innerHTML = "";

            question.options.forEach((option, index) => {

                const optionElement = document.createElement("label");

                optionElement.innerHTML = `<input type="radio" name="answer" value="${index}"> ${option}`;

                optionsElement.appendChild(optionElement);

            });

        }


        function showNextQuestion() {

            const selectedOption = document.querySelector("input[name='answer']:checked");

            if (selectedOption) {

                if (parseInt(selectedOption.value) === quizData[currentQuestion].answer) {

                    score++;

                }


                selectedOption.checked = false;

                currentQuestion++;

                if (currentQuestion < quizData.length) {

                    showQuestion(quizData[currentQuestion]);

                } else {

                    showResult();

                }

            }

        }


        function showResult() {

            questionContainer.style.display = "none";

            resultContainer.style.display = "block";

            scoreElement.innerText = score;

        }


        nextButton.addEventListener("click", showNextQuestion);

        showQuestion(quizData[currentQuestion]);

    </script>

</body>

</html>


Comments