skip to Main Content

I am creating a multiple choice question exam project using radio button but there is problem in clicking the submit button and going to next question, getting correct or incorrect as result

here is code of HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MCQ Quiz</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
   
   <div class="quiz_container">
     <form id="quiz_form" onsubmit="return submitquiz(event)"> 
       <div class="question">
         <h1> Sample question for quiz </h1>
          <p id="que-text">  1. What is the capital of the india ?</p>
           <div class="choices">
           <label >
              <input type="radio" value="0" name="choice" > Mumbai<br>
            </label>   
            <label >
                <input type="radio" value="1" name="choice"> Kolkata <br>
            </label>   
           <label >
              <input type="radio" value="2" name="choice"> Delhi <br>
           </label> 
            <label > 
              <input type="radio" value="3" name="choice"> Chennai <br>
            </label>
          </div>
            <div> <p id="result"> </p> </div>

            <button type="submit"> Submit </button>
      </form>

here is css

body
 {
  background-color: #ffffff;
  font-family: Arial, Helvetica, sans-serif;
  display: flex;

}

.quiz_container
{
    width: 600px;
    margin: auto;
    padding: 2em;
    background-color: #a9dcf0;
    border-radius: 10px;
    box-sizing: border-box;
    box-shadow: 0 0 5px black;
}

.question
{
  margin-bottom: 15px;
}

.choice
{
  display: flex;
  flex-direction: column;
}

label
{
  font-size: 1em;
}

button 
{  
  background-color: #28a745;
  color: antiquewhite;
  border: none;
  border-radius: 5px;
  cursor: pointer ;
  display:inline-block;
  padding: 10px 20px;
}


button:hover
{
  background-color: #218835;
}

#result
{
  margin-top: 15px;
  font-size: 1.2em;
} 

here is js

 const ques=[
     // questions 
 
  
    {question: "2. How many months are there in year ?",
     choices:[" 11", "13", "12", "10"],
     correct: "2"  },

    {question:"3. The largest contry of world (Area wise) ?",
     choices:["Russia", "Canada", "India ", "Brazil"],
     correct:" 0" },

   // {question:" 4.  ",
     //choices:[ " ", " ", " ", " ",],
     //correct: " "  },
    ];

    let currentQue= 0;
    let currentAns= 0;

    function showQue ()
    {
        const queText= document.getElementById("que-text");
        queText.textContent= question[currentQue].question;
    

    const choices= document.querySelectorAll(".choice");
    choices.forEach((choice,index)=> {choice.textContent= question[currentQue].choices[index];});

    const result = document.getElementById("result");
    result.textContent="";
    }

    function checkAnswer(selected) {
        const result = document.getElementById("result");
        if (selected === ques[currentQue].correct) 
       {
          result.textContent = "It is Correct!";
          correctAnswers++;
        }
         else 
        {
          result.textContent = " It is Incorrect!";
        }
      
        setTimeout(() => {
          currentQue++;
      
          if (currentQue< ques.length)
         {
            showQuestion();
          } 
          else 
          {
            const quizContainer = document.querySelector(".quiz_container");
            quizContainer.innerHTML = `<p>You got ${correctAnswers} out of ${ques.length} questions.</p>`;
          }
        }, 2000);
      }
      
      showQuestion();  

i am expecting that after submitting correct answer it will show as it is Correct! and if wrong than it is Incorrect!. than next question and so on . after completing all the questions it will show score. but i am stuck at Submit button and process after it.

2

Answers


  1. So you haven’t created a submitquiz function (declared as the form’s action)

    But just so you know: You really need a backend server for this. Javascript on the front end is completely insecure and any user who’s got some skills can open up the developer panel and find all the answers or otherwise hack the quiz.

    Bottom line: A backend server is the only way you can secure these quizes. Also, if you can get your hands on a backend server, you should look into templating, so that the UI can be reused for all quizes.

    Login or Signup to reply.
  2. Just by looking at your code i have seen four issues which are –

    1. submitquiz() function is missing from your js.
    2. You are calling showQuestion(); which is absent in your js.
    3. checkAnswer(selected) function is not being called from anywhere. You need to get the selected radio button’s value and pass it to the checkAnswer(selected).
    4. The variable correctAnswers is missing.

    Based on your description, I have made changes to address these issues and fulfill your requirements for the desired functionality. Here is the revised code:

    const questions = [
        {
            question: "1. What is the capital of India?",
            choices: ["Mumbai", "Kolkata", "Delhi", "Chennai"],
            correct: "2"
        },
        {
            question: "2. How many months are there in a year?",
            choices: ["11", "13", "12", "10"],
            correct: "2"
        },
        {
            question: "3. The largest country in the world (Area-wise)?",
            choices: ["Russia", "Canada", "India", "Brazil"],
            correct: "0"
        }
    ];
    
    let currentQuestionIndex = 0;
    let correctAnswersCount = 0;
    
    function showQuestion() {
        const question = questions[currentQuestionIndex];
        document.getElementById("que-text").textContent = question.question;
    
        const choicesContainer = document.querySelector(".choices");
        choicesContainer.innerHTML = ''; // Clear previous choices
        question.choices.forEach((choice, index) => {
            choicesContainer.innerHTML += `
                <label>
                    <input type="radio" name="choice" value="${index}"> ${choice}
                </label>
            `;
        });
    
        document.getElementById("result").textContent = "";
    }
    
    function submitQuiz(event) {
        event.preventDefault();
        const selected = document.querySelector('input[name="choice"]:checked');
        if (!selected) {
            alert("Please select an answer!");
            return false;
        }
    
        const selectedValue = selected.value;
        checkAnswer(selectedValue);
        return false;
    }
    
    function checkAnswer(selected) {
        const result = document.getElementById("result");
        if (selected === questions[currentQuestionIndex].correct) {
            result.textContent = "It is Correct!";
            correctAnswersCount++;
        } else {
            result.textContent = "It is Incorrect!";
        }
    
        setTimeout(() => {
            currentQuestionIndex++;
            if (currentQuestionIndex < questions.length) {
                showQuestion();
            } else {
                document.querySelector(".quiz_container").innerHTML = `
                    <p>You got ${correctAnswersCount} out of ${questions.length} questions.</p>
                `;
            }
        }, 2000);
    }
    
    showQuestion();
    <style>
            body {
                background-color: #ffffff;
                font-family: Arial, Helvetica, sans-serif;
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100vh;
                margin: 0;
            }
            .quiz_container {
                width: 600px;
                padding: 2em;
                background-color: #a9dcf0;
                border-radius: 10px;
                box-shadow: 0 0 5px black;
                box-sizing: border-box;
            }
            .question {
                margin-bottom: 15px;
            }
            .choices {
                display: flex;
                flex-direction: column;
            }
            label {
                font-size: 1em;
                margin-bottom: 5px;
            }
            button {
                background-color: #28a745;
                color: antiquewhite;
                border: none;
                border-radius: 5px;
                cursor: pointer;
                padding: 10px 20px;
            }
            button:hover {
                background-color: #218835;
            }
            #result {
                margin-top: 15px;
                font-size: 1.2em;
            }
        </style>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>MCQ Quiz</title>
    </head>
    <body>
        <div class="quiz_container">
            <form id="quiz_form" onsubmit="return submitQuiz(event)">
                <div class="question">
                    <h1>Sample question for quiz</h1>
                    <p id="que-text"></p>
                    <div class="choices"></div>
                    <div>
                        <p id="result"></p>
                    </div>
                    <button type="submit">Submit</button>
                </div>
            </form>
        </div>
    </body>
    </html>

    Hope this may help you. Good Luck!!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search