Creating a filter function that targets boolean values in an array object can be achieved using JavaScript

let quizQuestions = [
    {
        question: "What is the capital of France?",
        answers: [
            { text: "Paris", correct: true },
            { text: "Rome", correct: false },
            { text: "Berlin", correct: false },
            { text: "London", correct: false },
        ],
    },
    {
        question: "How many continents are there on Earth?",
        answers: [
            { text: "7", correct: true },
            { text: "5", correct: false },
            { text: "9", correct: false },
            { text: "3", correct: false },
        ],
    },
];

function displayQuestion(questionAndAnswers) {
  const shuffledAnswers = _.shuffle(questionAndAnswers.answers);
  questionTag.innerText = questionAndAnswers.question;
  answerTag[0].innerText = shuffledAnswers[0].text;
  answerTag[1].innerText = shuffledAnswers[1].text;
  answerTag[2].innerText = shuffledAnswers[2].text;
  answerTag[3].innerText = shuffledAnswers[3].text;
}

document.querySelectorAll(".answer").forEach((chosenAnswer) => {
  chosenAnswer.addEventListener("click", (event) => {
    if (quizQuestions.answers.correct == true) {
      console.log("Correct answer selected!");
    }
  });
})

Essentially, I have a set of quiz questions stored in an array with corresponding answers. When the questions are displayed on the screen, the answers are shuffled. The challenge lies in the last section of code below; how can I verify if the clicked value is the correct answer?

<h3 id="question"></h3>
        <div class="answers">
            <button id="answer1" class="answer"></button>
            <button id="answer2" class="answer"></button>
            <button id="answer3" class="answer"></button>
            <button id="answer4" class="answer"></button>
        </div>

Answer №1

Update the answer elements with a new attribute indicating if it is the correct answer. This way, you can easily validate it within the event listener.

let quizQuestions = [
    {
        question: "How many legs does a spider have?",
        answers: [
            { text: "6", correct: false },
            { text: "8", correct: true },
            { text: "10", correct: false },
            { text: "12", correct: false },
        ],
    },
    {
        question: "Which planet is known as the Red Planet?",
        answers: [
            { text: "Venus", correct: false },
            { text: "Mars", correct: true },
            { text: "Jupiter", correct: false },
            { text: "Saturn", correct: false },
        ],
    },
];

function displayQuestion(questionAndAnswers) {
  const shuffledAnswers = _.shuffle(questionAndAnswers.answers);
  questionTag.innerText = questionAndAnswers.question;
  shuffledAnswers.forEach(({text, correct}, i) => {
    answerTags[i].innerText = text;
    answerTags[i].dataset.correct = correct;
  });
}

document.querySelectorAll(".answer").forEach((answer) => {
  answer.addEventListener("click", (event) => {
    if (event.target.dataset.correct == 'true') {
      console.log("Correct Answer!");
    }
  });
})

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

Is it possible to link multiple references to a single Element/Node?

I am working on a function component that needs to pass the incoming ref from the parent to a div it is rendering. Additionally, I want to create and assign a separate ref inside the component to the same div. However, due to an element only accepting one ...

Ways to verify the presence of users in the Database

I have successfully retrieved the data with the code below, but I am encountering issues with my script's if and else statements. Any tips or advice on how to improve this functionality? server.post('/like', (req, res,next) => { var ...

FabricJS Canvas with a React DropDown Feature

While I have successfully created a TextBox on FabricJS Canvas, creating a Dropdown component has proven to be a challenge. The fabric.Textbox method allows for easy creation of text boxes, but no such built-in method exists for dropdowns in FabricJS. If y ...

Revising HTML content when Angular array is modified

I have a code snippet below where I am updating the value of an object in the first item of an array. However, I'm struggling to find a way to "refresh" the HTML view so that the changes are immediately reflected on the browser. var dataArr ...

Passing Props to a Functional Stateless Component in React

The AuthLinks component should display the notification count passed as the notificationCount prop in the Notifications Component. I need to access the notificationCount value in the AuthLinks component, but it seems like it should be available in AuthLin ...

Retrieve the content within a div using Jquery

Is it possible to extract the content from a <div> upon clicking a link? For example: Imagine there are two separate div elements on a webpage <div id="1" > This Is First Div </div> <div id="2" > This Is Second Div </div> & ...

What are the best scenarios for utilizing (a)synchronous calls?

Currently, I am working on a project for my office as a learning exercise. We have a tradition of bringing food every Monday, so I decided to create a program that displays each person's turn. My webpage can generate a calendar with a spare color colu ...

Using Ajax to implement the Modal IF functionality

Currently in the process of registering a domain, utilizing two modals in the process. Through Ajax, I have set it up so that if the response is 1, an alert stating that the domain is available is displayed. If the response is 0, an alert stating that the ...

How to retrieve the value of input in a Formik form when the onChange event occurs

Currently, I am working on creating a form using React JS and the Formik library. One issue I encountered was related to validation, specifically the need to replace invalid letters with an empty string. str.replace(/\D/, ''); The challenge ...

Issues with arrays and objects not functioning properly in local storage

Currently, I am working on implementing a TODO list that utilizes local storage to store data. Unfortunately, I have encountered an issue in my code that I am struggling to fix. In the getTaskArray() function, I retrieve an array from local storage using ...

Begin by introducing a fresh attribute to a JSON entity

Looking for help with modifying JSON data: var myVar = { "9":"Automotive & Industrial", "1":"Books", "7":"Clothing" }; I need to insert a new element at the beginning of the array, resulting in this: var myVar = { "5":"Electroni ...

Exploring the world of MVC4: Enhancing user experience with client-side

Solution: The answer provided by @www.innovacall.com is correct, I initially misunderstood it but now it works perfectly. Thank you for the help. Initial issue: I have been struggling with finding a solution to my problem. In my project, there is a mod ...

Adjusting the aspect ratio of an ortographic camera when resizing

Is there a method to configure an orthographic camera in THREE.JS in a way that: 1)It retains a consistent aspect ratio regardless of window resizing. This aspect ratio should remain constant and not be affected by the window's dimensions or aspect r ...

Placing <object> within the existing HTML form

If a user enters the values 12345 into an input box on my webpage and clicks a button, an object will appear below or instead of the form. The code I have for this functionality is: <form name="form" action="" method="post"> <input type="text" ...

How can I redirect to a different URL using Ajax when successful POST request is made?

Here is the code snippet I am working with: $.ajax({ type: "POST", url: "/pro_signup", data: { data: data, key: key }, dataType: "json", success: function (response) { document.getElementById("pu ...

Signaling an Event from a module in the node_modules directory to the Vue application

Is there a way to capture an event emitted by a node module and receive it in a Vue file? Sample code from the JavaScript node module: const EventEmitter = require('events') class Find extends EventEmitter { // code snippets here } class Fin ...

An error has occurred in the Next.js App: createContext function is not defined

While developing a Next.js application, I keep encountering the same error message TypeError: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function every time I try to run my app using npm run dev. This issue arises when attempting to co ...

Adjust the size of images using jQuery to perfectly fit the container dimensions

I am currently working on a script to automatically resize images that are too large for the container: $('img').each(function(i){ var parent_width = parseInt($(this).parent().width()), image_width = parseInt($(this).width()); ...

Should we employ getAttribute() or avoid it entirely? That is the ultimate query

Similar Topic: JavaScript setAttribute vs .attribute= javascript dom, how to handle "special properties" as versus attributes? On multiple occasions, I've encountered criticism in forums or Usenet about the way I access attributes i ...

Steps for permanently closing dismissible alerts in Bootstrap 4

On my MediaWiki site, my goal is to display a bootstrap 4 alert for new visitors on specific pages, and have it stay permanently dismissed after it is closed. The alert will be transcluded to multiple pages, but once dismissed, it should not reappear on an ...