I am having trouble with my quiz function as it only checks the answer correctly for the first question. Does anyone have suggestions on how to make it work for

Currently, I'm tackling a quiz project that was assigned to me during my bootcamp. My focus right now is on the checkAnswer function, which evaluates the answer selected by the player.

const startButton = document.querySelector(".start") as HTMLButtonElement;
startButton.addEventListener("click", () => {
  const presentation = document.querySelector(
    ".presentation"
  ) as HTMLDivElement;
  presentation.style.display = "none";
  questionContainer.style.display = "flex";
  displayQuestion(questions[currentQuestion]);
  console.log("je marche");
  checkAnswer(questions[currentQuestion].correctAnswer);
});

function checkAnswer(correctAnswer: string) {
  buttonListener(button1, correctAnswer);
  buttonListener(button2, correctAnswer);
  buttonListener(button3, correctAnswer);
  buttonListener(button4, correctAnswer);
}

function buttonListener(button: HTMLButtonElement, correctAnswer: string) {
  button.addEventListener("click", () => {
    if (button.textContent === correctAnswer) {
      console.log(`${button.textContent} is the right answer`);
      score += 10;
      currentQuestion++;
      button.textContent = "";
      console.log(
        `The current score is ${score} and the next question is number ${
          currentQuestion + 1
        }`
      );
      displayQuestion(questions[currentQuestion]);
      console.log(currentQuestion);
    } else if (button.textContent !== correctAnswer) {
      console.log(`${button.textContent} is not the right answer`);
      score -= 5;
      currentQuestion++;
      button.textContent = "";
      console.log(
        `The current score is ${score} and the next question is number ${
          currentQuestion + 1
        }`
      );
      displayQuestion(questions[currentQuestion]);
      console.log(currentQuestion);
    }
  });
}

Take a look at my repository for the complete code

Current Challenge:

  • Upon selecting an answer, the display of the subsequent question occurs automatically, which aligns with the intended behavior.
  • However, after answering the first question, the comparison made by the function registers incorrectly when moving to the second question. This discrepancy persists across all subsequent questions.

Potential Issue: The constant value of the correct answer remains unchanged between each question, causing the function to mistakenly evaluate the user's selection against the initial correct answer. This observation is corroborated by adjusting one of the answers in the second question to match the correct answer from the first question, resulting in the correct evaluation.

Attempted Solutions: I experimented with altering the correct answer by introducing a variable within the displayQuestion function, but this approach proved unsuccessful. Similarly, implementing a similar modification within the checkAnswer function did not yield the desired outcome.

I am seeking guidance to address this challenge without requesting a direct solution, aiming to regain my footing in resolving this issue.

Thank you for considering my inquiry!

Answer №1

It seems like you're encountering a challenge with adding a click event listener to your start button and getting stuck with the initial correct answer passed through. To solve this, consider implementing click event listeners on each button and finding a way to cycle through the correct answers within your questions object. Then, compare them with the text content of the selected button. There are various methods to achieve this - I recommend exploring querySelectorAll, shift, pop, and different types of loops.

Just remember that the issue arises from passing the correctAnswer only when the startButton is clicked.

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

The or operator in Typescript does not function properly when used as a generic argument

My current configuration is as follows: const foo = async <T>(a): Promise<T> => { return await a // call server here } type A = { bar: 'bar' } | { baz: 'baz' } foo<A>({ bar: 'bar' }) .then(response =& ...

Sending a file through an Ajax POST request to a PHP server

I am attempting to upload the HTML input file to my PHP file using a different method than the traditional synchronous HTML forms. The problem I am encountering is that it seems like I am not correctly POST'ing the input file to my PHP file because t ...

A guide on utilizing buttons within ion list items to execute actions independently for both the button and the list item

Currently, I have a list item with a button that is displayed based on a certain condition. My issue is that when I click the button, a popup should appear, but instead, it also navigates to the next page in the background. Can someone help me figure out h ...

Guide to initializing the state in pinia with Typescript

I am encountering an issue while trying to add typescript to a pinia store. Any suggestions on how to resolve this problem would be appreciated. The project currently utilizes pinia:^2.0.16 and Vue:3.2.37 The error message is as follows: Type '{}&a ...

retrieve the source code from all .js links found within the document

There is a file labeled urls.txt. https://website.tld/static/main_01.js https://website.tld/static/main_02.js https://website.tld/static/main_03.js .... All the source code from every .js file in allsource.txt needs to be extracted. Instructions: To ge ...

Error handling: Encountered unexpected issues while parsing templates in Angular 2

I'm a beginner with Angular 2 and I'm attempting to create a simple module, but encountering an error. app.component.html import { Component } from '@angular/core'; import { Timer } from '../app/modules/timer'; @Component({ ...

Navigating the intricacies of platform-specific settings in JavaScript

Currently, I am in the process of transferring an application from one PHP-based CMS to another (such as Wordpress, Joomla, etc.). I have established classes that enable my code to function seamlessly on each platform without any alterations (so far so goo ...

Issues with updating data using PUT routes in Slim Framework v3

After upgrading to Slim v3, all my GET and POST routes are functioning correctly, but the PUT routes are encountering issues. I have a class where I have implemented this: $this->slimObj->put('/path/{ID}', array($this, 'method')) ...

Is it possible to reverse the use of JQuery's .each() function without any additional plugins or modifications?

Similar Question: Reversing JQuery .each() Is there a better approach to using .each() in reverse? Currently, I am implementing it like this: var temp = []; $("#nav a").each(function() { temp.push($(this)); }); temp.reverse(); for(var i = 0; i ...

Hide the Select Column from the material-react-table

Can someone help me with hiding specific columns in the material-react-table component? I've searched the documentation but couldn't find any relevant information. import { useMemo, useState } from "react"; import { MaterialReactTable } ...

Enhancing material appearance by incorporating color gradient through the extension of three.js Material class using the onBeforeCompile method

In my three.js scene, I have successfully loaded an .obj file using THREE.OBJLoader. Now, I am looking to add a linear color gradient along the z-axis to this object while keeping the MeshStandardMaterial shaders intact. Below is an example of a 2-color l ...

Mysterious attributes of angular 6's <table mat-table> tag

This particular question regarding the angular material table has not been duplicated in any other discussions. Other similar questions pertain to angular versions 2-5, not version 6 The issue I am encountering is as follows: Can't bind to 'dat ...

The function of jQuery's .prop('defaultSelected') appears to be unreliable when used in Internet Explorer 9

Below is the code I am currently using: $selects = $('select'); $selects.val( $selects.prop('defaultSelected')); The purpose of this code is to reset the values of all select elements on my webpage. However, I am facing an issue in IE ...

Executing a Visual Basic subroutine from a jQuery dialog box

Currently, I have a form that includes a jQuery dialog creation. Within this dialog, there is a button generated from an ASP server control that should trigger a function in the code behind when clicked. However, I am encountering an issue where the functi ...

Is there a way to establish a connection between two excel entries using Angular?

In order to connect xlsx file records with their corresponding ids using angular, I am seeking a solution. To elaborate further: Let me provide an example for better understanding: Scenario 1 https://i.stack.imgur.com/25Uns.png Scenario 2 https://i ...

Firestore query is not displaying the expected data, resulting in an empty array being returned

I've encountered an issue where my query is returning an empty array. Despite double-checking for errors and typos in the query, no error messages are popping up. This problem arose while working on a learning project inspired by Firehip's NextJS ...

Encounter a Typescript error when dealing with "app.ws" while using express-ws

I have a small project in mind where I want to create a BabyCam that can be accessed from any web browser using a Raspberry Pi Zero. My plan is to set up a web socket using express-is to stream video to multiple clients. I'm utilizing the raspivid-str ...

Converting javascript html object lowercase

Is there a way to dynamically adjust the height of specific letters in my label? Right now, I am overriding the text for the elements: let element = document.getElementById('xxx') element.textContent = 'Label' I attempted using <sup ...

After transitioning to a different laptop, I encountered unexpected ES6 syntax errors while trying to compile my Vue project

I recently acquired a new laptop and encountered an issue. After pulling my Vue project from GitHub, I proceeded to run npm install, followed by npm run dev. ERROR Failed to compile with 1 errors 1:38:10 PM ...

Customize Bootstrap radio buttons to resemble standard buttons with added form validation styling

Is there a way to style radio buttons to look like normal buttons while maintaining their functionality and form validation? I have two radio buttons that need styling but should still behave like radio buttons. Additionally, I am utilizing Bootstrap for s ...