Is there a way to modify the color of my question post-submission?

Within my code, there are numerous queries that need to be addressed. Upon submission, I desire to alter the color of each question to green if the response is correct, or red if it is incorrect.

     
document.getElementById("submit-button").addEventListener("click", function() {
    var questions = document.getElementsByClassName("question");
    var totalQuestions = questions.length;
    var correctAnswers = 0;

    for (var i = 0; i < questions.length; i++) {
      var question = questions[i];
      var selectedOption = question.querySelector("input:checked");

      if (selectedOption) {
        var answer = selectedOption.value;
        var correctAnswer = question.getAttribute("data-correct-answer");
        if (answer === correctAnswer) {
          correctAnswers++;
        }
      }
    }

    var resultMessage = "You answered " + correctAnswers + " out of " + totalQuestions + " questions correctly.";
    alert(resultMessage);
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="question" data-correct-answer="c">
      <p>Question 1:</p>
      <p>What is the value of 2 + 2?</p>
      <label><input type="radio" name="q1" value="a"> a) 2</label>
      <label><input type="radio" name="q1" value="b"> b) 3</label>
      <label><input type="radio" name="q1" value="c"> c) 4</label>
    </div>

Could someone guide me through the process?

My attempts using ChatGPT and other online resources have proven to be futile. ChatGPT failed to comprehend the issue, and the internet provided no solutions.

Answer №1

To give a different look to correct and incorrect answers, you can use a dynamic class such as .correct and .incorrect respectively.

Your style declarations could be as follows:

<style>
  .correct {
    color: green;
  }

  .incorrect {
    color: red;
  }
</style>

Then, in your script:

(...)

if (selectedOption) {
        var answer = selectedOption.value;
        var correctAnswer = question.getAttribute("data-correct-answer");

        if (answer === correctAnswer) {
          correctAnswers++;
          /* Add class if answer is correct */
          question.classList.add("correct");
        } else {
          /* Add class if answer is incorrect */
          question.classList.add("incorrect");
        }
      }
    }

(...)

Answer №2

When referring to the question, I assume you are talking about the entire section within the DIV. In that case, assign an ID and a NAME to the DIV.

<div class="question" data-correct-answer="c" id="question" name="question">

By doing this, you can easily modify the color using either the ID or the Name. Typically, the ID is used more frequently, but it has become customary to include both attributes. By utilizing "document.getElementById()", the document will search for the specified ID within the parentheses. In this scenario, the ID is set as "question." The CSS attribute can be accessed with ".style" and the color attribute can be modified with ".color." Depending on the condition, you can determine the correct or incorrect answer...

if (answer === correctAnswer) {
  correctAnswers++;
  document.getElementById("question").style.color = "green";
} else {
  document.getElementById("question").style.color = "red";
}

Feel free to choose any shade or hue that you prefer and have fun with it!

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

Steps to clear a form after submitting it

Hello all, I have a rather complex form that sends a message successfully with an alert after submission. I'm wondering how I can clear the entire form once it has been submitted to make it simple? Below is my HTML Form and JavaScript code. I would l ...

React navigator appears stuck and unable to navigate between screens

I encounter an issue where my app closes when I press the switch screen button, but there is no error output displayed. I have checked for any version discrepancies and found no problem. The function I implemented for the button is functioning as expected ...

FormData enables uploading of several images through distinct fields simultaneously

Looking to upload images to the server before submitting the form? Unable to nest forms, FormData() is being utilized. The form includes a title and 5 images with captions. The goal is to initiate the upload once an image is selected without clicking &apo ...

mongojs implementation that allows for asynchronous query execution without blocking

Forgive me for asking what may seem like a silly question, but I am struggling to make this work. Currently, as part of my learning journey with node.js and mongojs, I have encountered the following issue: Below is my server.js file server.get("/", funct ...

How to incorporate an image within a div element without reliance on the <img> tag

I am dealing with HTML content <div> <img src="xyz.jpg"> </div> The challenge I am facing is fetching an image in hex format from a web service, converting it to JPEG, and displaying it inside a div. However, the <img src=""> ta ...

Is it possible to use both interfaces and string union types in TypeScript?

My goal is to create a method that accepts a key argument which can be either a string or an instance of the indexable type interface IValidationContextIndex. Here is the implementation: /** * Retrieves all values in the ValidationContext container. ...

Are Primereact and MUI JOY Styling at Odds?

here is the image of datatables and button I am currently using Primereact and MUI Joy in the same project, but I am facing an issue where the Primereact styling does not load properly. I'm not sure if it's due to a conflict with MUI Joy or some ...

Optimizing Open Graph tags for sharing WhatsApp links

I am utilizing Open Graph tags to optimize sharing on social media platforms. The image I have specified is 1200 x 630 pixels and displays correctly on Facebook as well as Whatsapp: <meta property="og:image" content="https://emotionathlet ...

Linking two div elements together with a circular connector at the termination point of the line

I am currently working on designing a set of cards that will showcase a timeline. I envision these cards to be connected by lines with circles at each end, for a visually appealing effect. At the moment, I have created the cards themselves but I am struggl ...

Retrieve the property of an object from within an array

I am dealing with an array structure like this: const arr = [{ name: 'One', id: 1 }, { name: 'Two', id: 2 } ]; My goal is to extract and return the name of the object if its id matches a certain value. After exp ...

You can disregard the first option in a multiple select box using jQuery

Imagine having multiple select boxes with the same options that are mutually exclusive. For instance, if Select Box A and Select Box B both have Option 1, Option 2, and Option 3, selecting Option 1 for Select Box A should make it unavailable in Select Box ...

What is the process for customizing the color of the focused label in Material UI through styling?

Recently, I delved into the world of JSS for styling and ran into an intriguing issue. My goal was to modify the color of a label in an InputLabel component when it is in focus state. After some tinkering, I managed to achieve this using the code snippet b ...

What impact does the use of CSS in emails have on various email clients and reading formats?

As I delve into customizing my very first (woocommerce) email template, I am considering the option of concealing data using CSS display: none. However, a few questions arise regarding the compatibility and support of CSS and display: none: Do all email ...

Troubleshooting: Why is my CSS Div tag failing to

Can someone help me figure out why the CSS isn't working when I try to use a div tag to style a page that I include with include 'login.php'; inside the <div> tag? My main goal is to overlay the form on the page, but for now I just wan ...

Using PHPs nth-child in media queries

There are multiple images on MyPage, typically displayed in rows of 6. However, the number of images per row adjusts based on browser size using media queries. The issue arises with the margin set for the last image in each row, as the nth-child property r ...

Transforming FormData string key names into a Json Object that is easily accessible

Recently, I encountered an issue where my frontend (JS) was sending a request to my backend (Node Typescript) using FormData, which included images. Here is an example of how the data was being sent: https://i.stack.imgur.com/5uARo.png Upon logging the r ...

Extracting information from a JSON data within an API

How can I retrieve data with a name tag from JSON data using Ajax? The function showCard is not functioning properly when I try to grab data with a name tag. My goal is to display the name of the API data when an img element with the class found is clicked ...

Having trouble with transferring JSON data as a string from POSTMAN to a node server

My JSON data structure is as follows: const json = { "name": "Peter", "age": 21 } After calling JSON.stringify(json), the result is: '{"name":"Peter","age":21}' I am currently us ...

"the content does not occupy the entire space of the parent

My TableRow expands across the width of the screen, and within it is a ListView with a layout_width set to match_parent. However, the ListView does not expand properly. This issue arose when I added two buttons in the next TableRow. Even after setting the ...

Is there a more efficient method for streamlining the Express-Validator middleware in a separate file

In my current project, there is a lot of validation required using Express-Validator. In each file, I find myself repeating the same validation code: //Validation and Sanitizing Rules const validationRules = [ param('tab').isString().isLength({ ...