Is there a way to incorporate a restart quiz button once the final question has been answered? Additionally, is there a method to display a specific div based on the quiz results?

This concept revolves around a quiz with multiple sets of questions and choices. Upon starting with a "Start the quiz button", users will go through 3 sets of questions, each with 2 choices, resulting in 8 possible outcomes.

  1. Each question utilizes radio buttons for user selection.
  2. Subsequent questions are presented one by one until all have been answered.
  3. Upon completing the quiz, a specific section will display based on the answers given, replacing the question sections.
  4. To restart the quiz, a "Restart quiz" button will be available on the results screen.

Answer №1

If you want to conceal the buttons, consider assigning an id to the list element:

<ul id="options">
    <li>
        <input type="radio" name="answer" id="answer1" class="answer">
        <label for="answer1" class="radio-text" id="choice1"></label>
    </li>
    <li>
        <input type="radio" name="answer" id="answer2" class="answer">
        <label for="answer2" class="radio-text" id="choice2"></label>
    </li>
</ul>

In the updateQuiz function within the else statement, add:

 optionsElement.style.display = "none";
to hide the list from being displayed.

For a reset functionality, introduce a button and additional element ids to control item visibility and user choices:

    <div class="row no-gutters intro-wrapper">
        <div class="col-12 mt-3 my-md-5">
            <div class="col-12 text-center">
                <p>Some title</p>
            </div>
        </div>
        <div class="quiz-container" id="quiz">
            <div class="start-btn-wrapper">
                <a class="start-btn" href="#" id="startQuiz">Start the quiz <span>&#9658;</span></a>
            </div>
            <div class="quiz-header">
                <h2 class="text-center" id="question"></h2>
                <ul id="options">
                    <li>
                        <input type="radio" name="answer" id="answer1" class="answer">
                        <label for="answer1" class="radio-text" id="choice1"></label>
                    </li>
                    <li>
                        <input type="radio" name="answer" id="answer2" class="answer">
                        <label for="answer2" class="radio-text" id="choice2"></label>
                    </li>
                </ul>
            </div>
            <button id="submit" class="btn btn-primary">Submit</button>
            <div>
              <p id = "outcome"></p>
            </div>
            <div>
              <button class="btn btn-primary" id="resetQuiz">Restart</button>
            </div>
        </div>
        <div class="quiz-outcome" id="quizOutcome">
            <div class="set-1">
                  <h2>Some text title1</h2>
                  <p>Some description etc etc</p>
            </div>
            <div class="set-2">
                <h2>Some text title2</h2>
                  <p>Some description etc etc</p>
            </div>
            <div class="set-3">
                <h2>Some text title3</h2>
                  <p>Some description etc etc</p>
            </div>
            <div class="set-4">
                <h2>Some text title4</h2>
                  <p>Some description etc etc</p>
            </div>
            <div class="set-5">
                <h2>Some text title5</h2>
                  <p>Some description etc etc</p>
            </div>
            <div class="set-6">
                <h2>Some text title6</h2>
                  <p>Some description etc etc</p>
            </div>
            <div class="set-7">
                <h2>Some text title7</h2>
                  <p>Some description etc etc</p>
            </div>
            <div class="set-8">
                <h2>Some text title8</h2>
                  <p>Some description etc etc</p>
            </div>
        </div>
    </div>
</div>
const quizData = [
  {
    question: "This is question number 1",
    choices: ["Answer 1-1", "Answer 1-2"],
  },
  {
    question: "This is question number 2",
    choices: ["Answer 2-1", "Answer 2-2"],
  },
  {
    question: "This is question number 3",
    choices: ["Answer 3-1", "Answer 3-2"],
  },
];

function determineOutcome(answers) {
  const outcomes = {
    "Answer 1-1,Answer 2-1,Answer 3-1":
      "Set 1",
    "Answer 1-2,Answer 2-1,Answer 3-1":
      "Set 2",
    "Answer 1-1,Answer 2-2,Answer 3-1":
      "Set 3",
    "Answer 1-2,Answer 2-2,Answer 3-1":
      "Set 4",
    "Answer 1-1,Answer 2-1,Answer 3-2":
      "Set 5",
    "Answer 1-2,Answer 2-1,Answer 3-2":
      "Set 6",
    "Answer 1-1,Answer 2-2,Answer 3-2":
      "Set 7",
    "Answer 1-2,Answer 2-2,Answer 3-2":
      "Set 8",
  };

  const combinationKey = answers.join(",");
  return outcomes[combinationKey] || "Could not determine your outcome.";
}

const questionElement = document.getElementById("question");
const optionsElement = document.getElementById("options");
const answerElements = document.querySelectorAll(".answer");
const radioTextElements = document.querySelectorAll(".radio-text");
const submitButton = document.getElementById("submit");
const startQuizButton = document.getElementById("startQuiz");
const quizBtnWrapper = document.querySelector(".start-btn-wrapper")
const resetButton = document.getElementById("resetQuiz");
const outcomeElement = document.getElementById("outcome");


resetButton.style.display = "none";
outcomeElement.style.display = "none";

// Initialize quiz index and user answers
let quizIndex = -1;
const userAnswers = [];

// Function to update the quiz content
function updateQuiz() {
  quizIndex++;

  if (quizIndex < quizData.length) {
    const currentQuestion = quizData[quizIndex];
    questionElement.textContent = currentQuestion.question;

    currentQuestion.choices.forEach((choice, index) => {
      radioTextElements[index].textContent = choice;
    });

    // Clear radio selections
    answerElements.forEach((answer) => {
      answer.checked = false;
      console.log("is this working1");

    });
  } else {
    optionsElement.style.display = "none";
      outcomeElement.style.display = "initial";
    questionElement.textContent = "Quiz Complete!";
    radioTextElements.forEach((text) => {
      text.textContent = "";
      console.log("is this working2");
    });
    submitButton.style.display = "none";
    console.log("is this working3");
  
    // Determine the outcome and display it 
    const outcome = determineOutcome(userAnswers);
    //const outcomeElement = document.createElement("p");
    outcomeElement.textContent = "Your outcome: " + outcome;
    //document.getElementById("quiz").appendChild(outcomeElement);
    resetButton.style.display = "initial";
  }
}

startQuizButton.addEventListener("click", () => {
  quizBtnWrapper.style.display = "none";
  updateQuiz();
});

submitButton.addEventListener("click", () => {
  const selectedAnswer = Array.from(answerElements).find((answer) => answer.checked);
  if (selectedAnswer) {
    userAnswers.push(selectedAnswer.nextElementSibling.textContent);
    updateQuiz();
  }
});

resetButton.addEventListener("click", () => {
  resetButton.style.display = "none";
  userAnswers.length = 0;
  quizIndex = -1;
  updateQuiz();
  quizOutcome.style.display = "none";
  optionsElement.style.display = "flex";
  submitButton.style.display = "initial";
  outcomeElement.style.display = "none";
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a new array containing the keys from an array of objects

My task involves extracting the key puppies from an array of objects and returning it in a new array: The input is an array of dogs structured like this: [ {breed: 'Labrador', puppies: ['Fluffy', 'Doggo', 'Floof&ap ...

Make sure to always nest child divs within their parent div to maintain

Hey there, I have a question that might seem silly to some. I've come across similar questions but none of the solutions worked for me. The problem I'm facing is with two nested divs - one inside the other. I want the inner div (taskbar-bar) to ...

The boolean validation function appears to be malfunctioning in the NodeJS environment

I am currently working on developing the node js API and I am fetching data using a URL query. get_posts_default?pageId=ge4JqBn9F0srzHnVFHmh&asking_post=false&asking_responce=false&maxSort=-1&minSort=-1&limit=20 This function is respo ...

Is there a definitive way to distinguish between scrollTop and scrollHeight in web development?

For instance, function checkingScroll(){ var newHeight = element.scrollHeight; var scrollTopValue = element.scrollTop; alert("The scrollHeight property is: " + newHeight + "px"); alert("The scrollTop property is: " + scrollTopValue ...

Is there a way to determine if a browser is operating in compatibility mode?

Is there a way to determine if the browser is in compatibility mode or not? I need to apply different CSS depending on the mode. ...

What is the best way to open an HTML file with Python without restrictions?

My HTML file is quite large, containing 4,574 words and 57,718 characters. However, when I try to read it using the .read() command, it only displays 3,004 words and 39,248 characters when I export it. Is there a way to read and export it without any lim ...

The Node.js controller is in disarray

As a newcomer to javascript, node.js, and backend development in general, I am tackling the task of creating a controller for handling login page requests. My confusion lies in extracting data from a MYSQL table, user authentication, and working with the J ...

Tips for crafting paragraphs that double as sieves

I'm trying to simplify and shorten this code. I have three HTML paragraphs acting as filters: "all", "positive," and "negative", referring to reviews. Each has a corresponding div for reviews: "allcont", "poscont", and "negcont". Clicking on any of th ...

When receiving a GET response after a server crash

Question: I am sending a Get request through Ajax every second and waiting for a response from the server. However, if my application crashes and I keep sending requests every second, I only receive a server timeout error (HTTP status code 502) with no oth ...

Check an array of objects for duplicate key-value pairs by cross-referencing other key-value pairs within the array using JavaScript

let selectedFruit = "mango" let fruitArray = [{fruit:"apple",locale:"US"}, {fruit:"orange",locale:"US"}, {fruit:"banana",locale:"US"}, {fruit:"apple",locale:"US"}, {fruit:"orange",locale:"IT"}, {fruit:"apple",locale: ...

What is the best way to iterate through and keep track of components within an Angular 2

Inquiring about counting components within my angular2 project. I have a total of 15 components - is there a way to loop through all of them or simply display their count? Preferably without involving them in the main app.components.html. ...

Vue.js: Conditionally preventing form submission

Currently, I am implementing form validation using VeeValidate. Although I prefer not to rely on JavaScript for form submission, I still want to prevent users from submitting the form if there are any errors present. However, using the code snippet below s ...

Executing the Correct Command to Import a CSV File into MongoDB using OSX Terminal

I am attempting to upload a TSV file into Mongodb, but my lack of familiarity with Terminal is causing issues. I keep receiving an error when trying to execute the following command. Can anyone provide guidance? /mongoimport --db webapp-dev --collection ...

Despite being used within useEffect with await, asynchronous function fails to wait for results

In my component, I am utilizing a cookie value to determine which component or div block to display. The functionality works correctly in the end, but there is a brief moment where it seems like the cookie value is not being checked yet. During this short ...

Discovering the server endpoint for the Star Wars SWAPI API: a step-by-step guide

I have been working on integrating a search query into the server-side endpoint, which interacts with swapi - the Star Wars API https://swapi.co/ to display a list of people by their names. Below is the fetch call made to the backend in App.js file using ...

Encountering difficulty retrieving the value of a hidden input with jQuery's find method

When a user clicks on the delete icon, I want to retrieve the value of the hidden input inside the "delete" class. However, I am getting an undefined result. Can someone please guide me on where I might be going wrong? <table class="items-list"> ...

Blank advertisements displayed on WordPress due to Google AdSense malfunction

My website on Wordpress can be found at . I encountered issues with the deprecated Adsense plugin for WordPress, so I created my own Adsense account. After verifying my site, I created a new ad unit and inserted its code into the body tag. The code for my ...

Obtain the current URL in a Node.js configuration file

In my application using the express framework, I have the following code in my app.js file: var express = require('express'); var app = module.exports = express(); var config = require('./config.js')(app, express); // Including ...

Custom stylesheet for individual users?

On my website, users can pick a template for their webpage. After selecting a template, I would like them to have the ability to customize certain styles like the font color. Is there a way to achieve this? I was thinking about saving the user's cus ...

Modifying the color of the accordion icon in Bootstrap 5.3 by utilizing a root variable

Is it possible to change the icon color of Bootstrap 5.3's accordion component to match the color of the heading text? I have successfully set the heading text color using a CSS root variable var(--body-text). However, when trying to override the SVG ...