Modifying several classes across different elements within a Svelte component

I developed a simple quiz application in which the user selects an answer and then clicks the 'check' button. If the selected answer is correct, it will be highlighted in green while incorrect answers are highlighted in red. Conversely, if the wrong answer is chosen, the selected option turns red while the correct answer is highlighted in green.

Currently, my code displays all answers as either green (if correct) or red (if incorrect). How can I modify it to achieve the desired result described above?

<script>
  let questionIndex = 0
  let selectedAnswer
  let correct
  let incorrect

  const quiz = [
    {
      question: 'What is the capital of France?',
      correct_answer: 'Paris',
      answers: ['Berlin', 'London', 'Madrid', 'Paris'],
    }
  ]

  const currentQuestion = quiz[questionIndex]
  const correctAnswer = currentQuestion.correct_answer

  const checkAnswer = () => {

    if (selectedAnswer  == correctAnswer) {
      correct = true
    }
        else {
            incorrect = true
        }

    }

</script>

<style>

  .correct {
    background-color: aquamarine;
  }

  .incorrect {
    background-color: red;
  }

</style>

<main>
  <h3>{quiz[questionIndex].question}</h3>

    <label class:correct class:incorrect>
                <input
                type="radio"
                bind:group={selectedAnswer}
                value={quiz[questionIndex].answers[0]} />
            {quiz[questionIndex].answers[0]}
        </label>
    
    <label class:correct class:incorrect>
                <input
                type="radio"
                bind:group={selectedAnswer}
                value={quiz[questionIndex].answers[1]} />
            {quiz[questionIndex].answers[1]}
      </label>

    <label class:correct class:incorrect>
                <input
                type="radio"
                bind:group={selectedAnswer}
                value={quiz[questionIndex].answers[2]} />
            {quiz[questionIndex].answers[2]}
      </label>

    <label class:correct class:incorrect>
                <input
                type="radio"
                bind:group={selectedAnswer}
                value={quiz[questionIndex].answers[3]} />
            {quiz[questionIndex].answers[3]}
      </label>

  <button on:click={checkAnswer}>Check</button>

</main>

Answer №1

Your approach seems to be redundant, consider implementing a loop to streamline the process.

Now, for each individual item, we are aiming for the following outcomes:

  • Add a correct class if the button has been clicked and the item is the correct answer.

  • Add an incorrect class if the button has been clicked and either (a) the answer is correct but the item is not the right answer, or (b) the answer is incorrect but the item is selected as the answer.

This translates into the following conditions for the classes:

answered && value === correctAnswer

For the incorrect class, here's the more complex condition (though I must say, your requirements are a bit convoluted which adds to the code complexity):

answered && (
  (correct && value !== correctAnswer) 
  || (!correct && value === selectedAnswer)
)

In terms of code implementation, it would look something like this:

<script>
  const questionIndex = 0

  let selectedAnswer
  let answered = false

  const quiz = [
    {
      question: 'What is the capital of France?',
      correct_answer: 'Paris',
      answers: ['Berlin', 'London', 'Madrid', 'Paris'],
    },
  ]

  // make this reactive!
  $: currentQuestion = quiz[questionIndex]
  $: correctAnswer = currentQuestion.correct_answer

  $: correct = selectedAnswer === correctAnswer

  const checkAnswer = () => {
    answered = true
  }

  const reset = () => {
    answered = false
  }
</script>

<main>
  <h3>{quiz[questionIndex].question}</h3>

  {#each quiz[questionIndex].answers as value}
    <label
      class:correct={answered && value === correctAnswer}
      class:incorrect={answered && ((correct && value !== correctAnswer) || (!correct && value === selectedAnswer))}>
      <input type="radio" bind:group={selectedAnswer} {value} />
      {value}
    </label>
  {/each}

  <button on:click={checkAnswer}>Check</button>
  <button on:click={reset}>Reset</button>

</main>

<style>
  .correct {
    background-color: aquamarine;
  }
  .incorrect {
    background-color: red;
  }
</style>

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

Transferring a Query between Domains with the Help of JavaScript

It is necessary to develop a function that generates a query based on the user's input of "Test" in an INPUT on Site A (SiteA.com) and then redirects to Site B within the same window, passing along the query (SiteB.com/search.aspx?k=test). Code snipp ...

What is the best way to transfer a JSX element from a child component to its parent component?

Is it acceptable to send the JSX element from a parent component to a child component through props? From my understanding, using `useState` to store JSX elements is not recommended. Therefore, I can't just pass a callback down to the child and then ...

Connect a nearby dependency to your project if it has the same name as an npm repository

What is the best way to npm link a local dependency that has the same name as a project in the npm registry, like https://registry.npmjs.org/react-financial-charts? Here is an example: cd ~/projects/react-financial-charts // Step 1: Navigate to the packa ...

Can you guide me on implementing AWS SDK interfaces in TypeScript?

Attempting to create an SES TypeScript client using AWS definitions file downloaded from this link My approach so far: /// <reference path="../typings/aws-sdk.d.ts" /> var AWS = require('aws-sdk'); var ses:SES = new AWS.SES(); The error ...

How can I design a form that resembles the sign-in form used by Google?

Currently, I am in the process of creating a contact form for a website that is inspired by the design of Google's material sign-in form. I have successfully implemented an effect where clicking on the input field causes the label to change its posit ...

Using JavaScript variables within the value section of a JSON is a common requirement for developers

var averageTemperature = req.params.rating; var destinationName = req.params.name; var query = { "results.name": destinationName }; var updateQuery = { $set: { "results.$.rating": averageTemperature } }; mach.update(query, updateQuery, function(err, res ...

The function Promise.all typically yields an array with nested arrays

Inside my node Router, the following code snippet is implemented: router.get("/single-base/:id", (req, res) => { Base.find({ _id: req.params.id }) .then(bases => { let basefetches = []; for (let base of bases) { ...

Finding a solution to the type issue of error handling in Route Handler with NextJS

I'm working on a route handler located at app/api/transactions/route.ts. Here's a snippet of the code: import { NextRequest, NextResponse } from "next/server"; import { AxiosError } from "axios"; import axios from "../axi ...

Understanding the extent of variables in Javascript

I'm struggling to comprehend the scope of 'this' in this particular situation. I can easily call each of these functions like: this.startTracking(); from within the time tracker switch object. However, when attempting to execute the code: Dr ...

Passing PHP loop values to JavaScript

In my current project, I made a decision to avoid using a database and instead opted for files and folders. Each folder in a directory is represented as a button, clicking on which displays a list of files within that folder on the screen. Now, my challeng ...

Transforming React Redux reducer to hooks for a more modern approach

I am in the process of creating a login and registration application. I need to change a reducer that is currently being used for a class-based component to work with hooks instead. Here is the existing reducer: import { SET_CURRENT_USER, USER_LOADING } fr ...

Injecting a full browser-screen DIV into the body of the webpage

Recently, I was tasked with developing a script that could be utilized on any website. As a test, I decided to use the Google search results page. My goal is simple - to have a full-screen semi-transparent div displayed on any site for cookie notification ...

What is the best way to input information into my Google spreadsheet with React JS?

After using https://github.com/ruucm/react-google-sheets as a reference, I encountered a persistent gapi 404 error whenever I tried to run the code. It seems like the GitHub link might not exist, causing my app to fail. However, I could be mistaken. Is t ...

What is the proper method for initiating an ajax request from an EmberJs component?

Curious to learn the correct method of performing an ajax call from an Ember component. Let's say, for instance: I am looking to develop a reusable component that allows for employee search based on their Id. Once the server responds, I aim to update ...

Protecting website pages on both the admin and user side in Next.js 14 to ensure maximum security

I'm currently using nextjs 14 and I am working on developing a website similar to a property app. It will have an admin dashboard and a user side. How can I ensure the security of both the admin and user sides, and what should my folder structure look ...

Using AREA Coordinates to create a custom Image Map with Image-Based Rollovers, incorporating jQuery for enhanced functionality if desired

I am looking for a solution similar to this: http://plugins.jquery.com/project/maphilight However, instead of just adding a border or fill color to <AREA> tags on rollover, I need them to display a background image. The image should be clipped by t ...

Is there an npm module available that can automate a daily task at a specified time in a Node.js environment?

Searching for an NPM Module to integrate into a Node.js application that can send notifications via email and SMS daily at 9am local time. Any suggestions or solutions would be greatly appreciated! ...

When access to Ajax .responseText in an alert it can be displayed, however it cannot be stored in a variable or

var response_var=""; // Added for debugging purposes ajax.onreadystatechange = function() { if (ajax.readyState == 4 & ajax.status == 200) { response_var = ajax.responseText; alert(ajax.responseText); // This alerts properly (some text ...

Issues with image uploads in Node.js database storage

Trying to update an image using the put method is resulting in a 'filename' undefined error. Interestingly, the image updates successfully when editing without changing the image. The code snippet below shows the implementation: app.put('/a ...

My array contains a list, and I need to determine how to ensure that a specific element is displayed first based on a condition in the mapping

Here is the object. let newObj = { firstValue:"abc", content:[ { "value": "123", "checked": true }, { "value": "456", "checked": false }, { "value": "789", "checked": tr ...