Changing the background color of a clicked checkbox can be done by using CSS

Currently, I am working on creating an exam page that features choices with checkboxes. My goal is to have the background of a selected choice change color. However, I am encountering some obstacles.

To view the codes and screen, please click here

Here is the HTML code snippet:

<div class="questions">
  <div class="questions-left-column">
    <div class="question-area">
      <p>QUESTION</p>
      <div class="choices">
        <div class="choice answer" id="1answer">
          <input id="choice-1a" type="radio" name="radio1" />
          <label for="choice-1a">
            <strong>A.</strong>
            Option A
          </label>
        </div>
        <div class="choice">
          <input id="choice-1b" type="radio" name="radio1" />
          <label for="choice-1b">
            <strong>B.</strong>
            Option B
          </label>
        </div>
        <div class="choice">
          <input id="choice-1c" type="radio" name="radio1" />
          <label for="choice-1c">
            <strong>C.</strong>
            Option C
          </label>
        </div>
        <div class="choice">
          <input id="choice-1d" type="radio" name="radio1" />
          <label for="choice-1d">
            <strong>D.</strong>
            Option D
          </label>
        </div>
        <div class="choice">
          <input id="choice-1e" type="radio" name="radio1" />
          <label for="choice-1e">
            <strong>E.</strong>
            Option E
          </label>
        </div>
      </div>
      <div class="show-answer-button-container">
        <label class="show-answer">
          <fieldset hidden class="answers">
            <strong>Correct Answer: </strong>
            A
          </fieldset>
          <button type="button" onclick="checkAnswers()">Check Answers</button>
        </label>
      </div>
    </div>
  </div>
</div>

Provided below is the CSS code portion:

.selectt {
  display: none;
}
.questions {
  display: flex;
  justify-content: center;
  border: 0.3px solid gray;
  padding: 10px;
}
.questions-left-column {
  flex-direction: column;
  border-right: 1px solid black;
  width: 400px;
  padding-right: 100px;
}
.question-area {
  margin-bottom: 30px;
  border: 0.3px solid gray;
  padding: 10px;
}
.choice {
  width: 350px;
  padding: 0.5rem;
  align-content: left;
  justify-self: center;
  border: 1px solid darkgrey;
}

.choice input[type="radio"]:checked + label {
  padding: 0.5rem;
  background: rgb(226, 182, 182);
  cursor: default;
}
input {
  visibility: hidden;
}

label {
  cursor: pointer;
}

.show-answer-button-container {
  margin: 10px;
}

.show-answer {
  margin-top: 0.5rem;
  align-items: right;
  padding: 0.1rem;
  border: 0.5px solid rgb(119, 108, 108);
  background: rgb(133, 183, 212);
  color: white;
  border-radius: 0.2rem;
}

Lastly, here is the JS code section provided:

function checkAnswers() {
  var elements = document.getElementsByClassName("choice answer");
  for (var i = 0; i < elements.length; i++) {
    elements[i].style.backgroundColor = "lightgreen";
  }
}

The issues that I am currently facing include:

  • After selecting a choice, only the background color of the text changes rather than the entire option box.

  • When clicking the 'Show Answer' button, the correct answer is displayed with a green background. However, if the chosen option matches the answer text's background, it turns purple while the box's background remains green.

I appreciate any assistance provided!

Answer №1

To implement a JavaScript function that adds an onclick event to the label, allowing you to access the parent style and update the background, you must iterate through the elements first to add the click event and then loop again to reset the correct background value upon clicking.

Below is a basic example (which can be further optimized) demonstrating how to add or remove a class:

function checkAnswers() {
  var elements = document.getElementsByClassName("choice answer");
  for (var i = 0; i < elements.length; i++) {
    elements[i].style.backgroundColor = "lightgreen";
  }
}
/* added */

const choices = document.querySelectorAll(".choice label");// get them all
// add onclick on labels found
for (let i = 0; i < choices.length; i++) {
  choices[i].addEventListener("click", () => {
    check(i);
  });
}
// triggered from the label click 
function check(el) {
  // reset all to none
  for (let ii = 0; ii < choices.length; ii++) {
    choices[ii].parentNode.classList.remove("selected");
  }
  // reset the label's parent classList
  choices[el].parentNode.classList.add("selected");
}
.selectt {
  display: none;
}

.questions {
  display: flex;
  justify-content: center;
  border: 0.3px solid gray;
  padding: 10px;
}

.questions-left-column {
  flex-direction: column;
  border-right: 1px solid black;
  width: 400px;
  padding-right: 100px;
}

.question-area {
  margin-bottom: 30px;
  border: 0.3px solid gray;
  padding: 10px;
}

.choice {
  width: 350px;
  padding: 0.5rem;
  align-content: left;
  justify-self: center;
  border: 1px solid darkgrey;
}

.choice input[type="radio"]:checked+label {
  padding: 0.5rem;

  cursor: default;
}

input {
  visibility: hidden;
}

label {
  cursor: pointer;
}

.show-answer-button-container {
  margin: 10px;
}

.show-answer {
  margin-top: 0.5rem;
  align-items: right;
  padding: 0.1rem;
  border: 0.5px solid rgb(119, 108, 108);
  background: rgb(133, 183, 212);
  color: white;
  border-radius: 0.2rem;
}

.selected {
  background: rgb(226, 182, 182);
}
<div class="questions">
  <div class="questions-left-column">
    <div class="question-area">
      <p>QUESTION</p>
      <div class="choices">
        <div class="choice answer" id="1answer">
          <input id="choice-1a" type="radio" name="radio1" />
          <label for="choice-1a">
            <strong>A.</strong>
            Option A
          </label>
        </div>
        <div class="choice">
          <input id="choice-1b" type="radio" name="radio1" />
          <label for="choice-1b">
            <strong>B.</strong>
            Option B
          </label>
        </div>
        <div class="choice">
          <input id="choice-1c" type="radio" name="radio1" />
          <label for="choice-1c">
            <strong>C.</strong>
            Option C
          </label>
        </div>
        <div class="choice">
          <input id="choice-1d" type="radio" name="radio1" />
          <label for="choice-1d">
            <strong>D.</strong>
            Option D
          </label>
        </div>
        <div class="choice">
          <input id="choice-1e" type="radio" name="radio1" />
          <label for="choice-1e">
            <strong>E.</strong>
            Option E
          </label>
        </div>
      </div>
      <div class="show-answer-button-container">
        <label class="show-answer">
          <fieldset hidden class="answers">
           <strong>Correct Answer: </strong>
            A
          </fieldset>
          <button type="button" onclick="checkAnswers()">Check Answers</button>
        </label>
      </div>
    </div>
  </div>
</div>

Answer №2

Check out this solution for modifying the CSS classes: http://jsfiddle.net/symfou/phw25ydg/26/

Here is the updated CSS:

.choice {
    position: relative;
    width: 350px;
    padding: .5rem;
    align-content: left;
    justify-self: center;
    border: 1px solid darkgrey;
}

.choice input[type="radio"]:checked + label strong{
    padding-left: 25px;
}

.choice input[type="radio"]:checked + label {
    padding: .5rem 0;
    background-color:rgb(226, 182, 182);
    cursor: default;
    position: absolute;
    width: 100%;
    left: 0;
    top: 0;
    margin: 0;
}

Answer №3

Here is a Code snippet demonstrating the use of onchange event in input

function validateSelection() {
  var elements = document.getElementsByClassName("choice answer");
  for (var i = 0; i < elements.length; i++) {
    elements[i].style.backgroundColor = "lightgreen";
  }
}

function updateSelection() {
  Array.prototype.forEach.call(document.getElementsByClassName('option'), function(el) {
    let elements = document.getElementsByClassName("choice answer");
    if (el.checked) {
      el.parentNode.style.backgroundColor = "rgb(226, 182, 182)";
    } else {
      el.parentNode.style.backgroundColor = "";
    }
  });
}
.selectt {
    display : none;
}
.questions {
    display: flex;
    justify-content: center;
    border: .3px solid gray;
    padding: 10px;    
}
.questions-left-column {
    flex-direction: column;
    border-right: 1px solid black;
    width: 400px;
    padding-right: 100px;
    }
.question-area {
    margin-bottom: 30px;
    border: .3px solid gray;
    padding: 10px;
}
.choice {
    
    width: 350px;
    padding: .5rem;
    align-content: left;
    justify-self: center;
    border: 1px solid darkgrey;
}

input {
    visibility:hidden;
}

label {
    cursor: pointer;
}

.show-answer-button-container {
    margin: 10px;
}

.show-answer {
    margin-top: .5rem;
    align-items: right;
    padding: .1rem;
    border: .5px solid rgb(119, 108, 108);
    background: rgb(133, 183, 212);
    color: white;
    border-radius: .2rem;
}
<div class="questions">
  <div class="questions-left-column">
    <div class="question-area">
      <p>QUESTION</p>
      <div class="choices">
        <div class="choice answer" id="1answer">
          <input id="choice-1a" type="radio" name='radio1' class="option" onchange="updateSelection()">
          <label for="choice-1a">
            <strong>A.</strong>
            Option A
          </label>
        </div>
        <div class="choice">
          <input id="choice-1b" type="radio" name='radio1' class="option" onchange="updateSelection()">
          <label for="choice-1b">
            <strong>B.</strong>
            Option B
          </label>
        </div>
        <div class="choice">
          <input id="choice-1c" type="radio" name='radio1' class="option" onchange="updateSelection()">
          <label for="choice-1c">
            <strong>C.</strong>
            Option C
          </label>
        </div>
        <div class="choice">
          <input id="choice-1d" type="radio" name='radio1' class="option" onchange="updateSelection()">
          <label for="choice-1d">
            <strong>D.</strong>
            Option D
          </label>
        </div>
        <div class="choice">
          <input id="choice-1e" type="radio" name='radio1' class="option" onchange="updateSelection()">
          <label for="choice-1e">
            <strong>E.</strong>
            Option E
          </label>
        </div>
      </div>
      <div class="show-answer-button-container">
        <label class="show-answer">

          <fieldset hidden class="answers">
            <strong>Correct Answer: </strong>
            A
          </fieldset>

          <button type="button" onclick="validateSelection()">Validate Answers</button>

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

Utilizing custom template tags with script tags for componentization within Django applications

Currently working on a Django project with multiple apps. One of the main apps serves as the base, housing global elements like CSS, JS, and custom template tags (referred to as CTTs). I'm interested in creating CTTs that contain HTML and script tags ...

A method for generating CSS code from the structure of an HTML document

I am currently working on developing a recursive function that takes an HTML document tree and generates formatted CSS using only child operators (>), but I seem to be stuck. If you could provide some hints or ideas, I would greatly appreciate it. The ...

What is the best way to exchange variables between siblings?

I'm completely new to working with Polymer, so feel free to share all the details! Currently, I have a simple webpage following a standard layout. My main goal is to understand how I can connect the #nav component variable currentSelection with the # ...

What types of video formats will be accepted?

I tried searching on Google but couldn't find the answer. I am curious to know, when using an input file like this: <input type="file" accept="video/*"> Which video formats are allowed for upload? I attempted to upload a .flv file and the ...

Navigate back to the previous slide utilizing slick and jquery

I am facing an issue with my slides that have multiple calls to actions opening different slide on click For example, if a user is on slide number 1 and clicks a button to open slide number 5, then upon clicking the go back button it should return to slid ...

The issue of linking .then() functions

I've been struggling to grasp the concept of Promises/then-ables for a while now. Currently, I am working with NextJS. My goal is to chain together the following steps: Retrieve data from an API Save the data Modify the data to create a component (w ...

HTML formatting for text

I recently created an HTML website using Dreamweaver. I faced an issue while trying to design a section within an article using tables to incorporate both text and images. Unfortunately, the tables did not have rounded edges as I desired. I am reaching out ...

Using Javascript and ExtJS to retrieve the Codemirror Editor using a textarea

Hello to the wonderful stackoverflow community, I recently incorporated a Codemirror Editor into my ExtJSProject like this: addCodeMirrorPanel: function() { this.getAixmFormarea().add(Ext.widget({ xtype: 'textarea', fieldLabe ...

Show the text based on the current count of the counter

Currently, I have a simple Javascript counter function: <body> <script type="text/javascript"> var clicks = 0; function onClick() { clicks += 1; document.getElementById("clicks").innerHTML = clicks; }; </ ...

Steps for iterating through an array within an object

I currently have a JavaScript object with an array included: { id: 1, title: "Looping through arrays", tags: ["array", "forEach", "map"] } When trying to loop through the object, I am using the following ...

Steps to modify the CSS of a custom component in Angular 8

I have been attempting to override the css of a custom component selector, however, my attempts have been unsuccessful. I have tried using ":ng-deep" but it hasn't worked. How can I go about finding a solution for this issue? app.component.html: < ...

Best practices for implementing the <head> tag in an Angular directive

After attempting the solution provided in this post for my Angular app, I ran into some issues. To try and resolve the problem, I decided to introduce a custom tag (<mytag>) into the head section, which allowed me to get the directive working by subs ...

The GET request for a "places" endpoint in a node js application is experiencing issues

Today marks my second day working with node js and mongo. I've explored different tutorials and currently, I'm attempting to follow this specific one: https://github.com/amejiarosario/todoAPIjs/commit/d3be6a287e8aff39ab862971da4f050d04e552a ...

Linking all styles with Angular 2

Is it possible to apply a style when the exact nature of that style is unknown? Consider a scenario where I have a model containing string variables defining styles, as shown below: myStyle1:string="margin-left:10px"; myStyle2:string="margin ...

What is the reason behind arr.reverse() flipping the original array?

My goal is to reverse an array and store the reversed version in a new array without altering the original array. Here is the code I am using: var arr= ["1", "2", "5"] var arrTwo = arr.reverse(); console.log(arrTwo) \\ ["5" , "2" , "1"] console. ...

Ways to prevent this column from taking up vertical space

When in desktop mode, I am facing an issue where the image is creating a gap between the "full name" and "Form Number" columns. Is there a way to adjust it so that the full name column starts right below the form number column? I know I could simply place ...

What is the reason that property spreading is effective within Grid components but not in FormControl components?

Explore the sandbox environment here: https://codesandbox.io/s/agitated-ardinghelli-fnoj15?file=/src/temp4.tsx:0-1206. import { FormControl, FormControlProps, Grid, GridProps } from "@mui/material"; interface ICustomControlProps { gridProps?: ...

Assign a different color to every other pair of rows

Here is the current table I am working with: <table> <tr> <td>a</td> </tr> <tr> <td>b</td> </tr> <tr> <td>c</td> </tr> <tr> ...

I keep running into an issue whenever I attempt to import material ui icons and core - a frustrating error message pops up stating that the module cannot be found

[I keep encountering this error message when attempting to utilize @material-ui/core and icons] `import React from "react"; import "./Sidebar.CSS"; import SearchIcon from "@material-ui/icons/Search"; const Sidebar = () => { return ( <> ...

Is it possible to handle user roles solely using JavaScript?

Hey there! I'm new to front-end development and I have a question. Can JavaScript alone be used to manage user authorities? I'm interested in creating a Student Management System with login features where the admin can add, delete, and update stu ...