Switch the background color when a radio button is chosen

For my quiz on test practice with an array of questions, each question includes five radio buttons, but only one is correct. Initially, all five options have a gray background. Upon selecting a wrong option, it changes to red. If another incorrect option is chosen, the new one turns red while the previous one reverts to gray. However, upon choosing the correct answer, it switches to green while the rest remain gray.

$(document).ready(function() {
  $("input[value='wrong']").click(function() {
    $("label").css("background-color", "red");
  });
  $("input[value='right']").click(function() {
    $("label").css("background-color", "green");
  });
});
.option {
  background: #eee;
  display: block;
  padding: 5px 10px 5px;
  color: #000;
  text-decoration: none;
  -moz-border-radius: 6px;
  -webkit-border-radius: 6px;
  -khtml-border-radius: 6px;
  border-radius: 6px;
  box-shadow: inset 0px 1px 3px rgba(0, 0, 0, 0.6);
  -moz-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.6);
  -webkit-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.6);
  text-shadow: 0px -1px 1px rgba(0, 0, 0, 0.25);
  border-bottom: 1px solid rgba(0, 0, 0, 0.25);
  position: relative;
  cursor: pointer;
  text-decoration: none;
  margin-bottom: 10px;
}
input[type="radio"] {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form3">
  <input type="radio" name="option" value="wrong" class="option1">
  <label class="option">Option 1</label>
  <input type="radio" name="option" value="wrong" class="option2">
  <label class="option">Option 2</label>
  <input type="radio" name="option" value="wrong" class="option3">
  <label class="option">Option 3</label>
  <input type="radio" name="option" value="right" class="option4">
  <label class="option">Option 4</label>
  <input type="radio" name="option" value="wrong" class="option5">
  <label class="option">Option 5</label>
</form>

How do I achieve this functionality using JQuery?

Answer №1

To start, you'll need to adjust your HTML code.

Enclose each input tag within a label tag.

For example:

<label class="option">
   <input type="radio" name="option" value="wrong" class="option1">Option 1
</label>

Next, update your CSS to hide the radio button but make it clickable:

input[type="radio"] {
  opacity: 0;
  margin: 0;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
}

Additionally, use two helper classes:

.right {
  background-color: green;
}
.wrong {
  background-color: red;
}

Finally, update your JavaScript as follows:

$(document).ready(function() {
  $("input[value='wrong']").click(function() {
    $(this).parent()
      .addClass("wrong")
      .siblings().removeClass("right wrong");
  });
  $("input[value='right']").click(function() {
    $(this).parent()
      .addClass("right")
      .siblings().removeClass("right wrong");
  });
});

Code Snippet:

$(document).ready(function() {
  $("input[value='wrong']").click(function() {
    $(this).parent()
      .addClass("wrong")
      .siblings().removeClass("right wrong");
  });
  $("input[value='right']").click(function() {
    $(this).parent()
      .addClass("right")
      .siblings().removeClass("right wrong");
  });
});
.option {
  background: #eee;
  display: block;
  padding: 5px 10px 5px;
  color: #000;
  text-decoration: none;
  -moz-border-radius: 6px;
  -webkit-border-radius: 6px;
  -khtml-border-radius: 6px;
  border-radius: 6px;
  box-shadow: inset 0px 1px 3px rgba(0, 0, 0, 0.6);
  -moz-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.6);
  -webkit-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.6);
  text-shadow: 0px -1px 1px rgba(0, 0, 0, 0.25);
  border-bottom: 1px solid rgba(0, 0, 0, 0.25);
  position: relative;
  text-decoration: none;
  margin-bottom: 10px;
}
input[type="radio"] {
  opacity: 0;
  margin: 0;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
}
.right {
  background-color: green;
}
.wrong {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form3">
  <label class="option">
    <input type="radio" name="option" value="wrong" class="option1">Option 1
  </label>
  <label class="option">
    <input type="radio" name="option" value="wrong" class="option2">Option 2
  </label>
  <label class="option">
    <input type="radio" name="option" value="wrong" class="option3">Option 3
  </label>
  <label class="option">
    <input type="radio" name="option" value="right" class="option4">Option 4
  </label>
  <label class="option">
    <input type="radio" name="option" value="wrong" class="option5">Option 5
  </label>
</form>

Answer №2

Utilize data-attributes for this task. Take a look at my code snippet.

$(document).ready(function() {
  $("label").click(function() {
    if ($(this).data('attr') == 'wrong') {
      $(this).css("background", "red");
    } else {
    $(this).css("background", "green");}
  });
});
.option {
  background: #eee;
  display: block;
  padding: 5px 10px 5px;
  color: #000;
  text-decoration: none;
  -moz-border-radius: 6px;
  -webkit-border-radius: 6px;
  -khtml-border-radius: 6px;
  border-radius: 6px;
  box-shadow: inset 0px 1px 3px rgba(0, 0, 0, 0.6);
  -moz-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.6);
  -webkit-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.6);
  text-shadow: 0px -1px 1px rgba(0, 0, 0, 0.25);
  border-bottom: 1px solid rgba(0, 0, 0, 0.25);
  position: relative;
  cursor: pointer;
  text-decoration: none;
  margin-bottom: 10px;
}
input[type="radio"] {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form3">
  <input type="radio" name="option" data-attr="wrong" class="option1">
  <label class="option" data-attr="wrong">Option 1</label>
  
  <label class="option" data-attr="wrong">Option 2</label>
  
  <label class="option" data-attr="wrong">Option 3</label>
  
  <label class="option" data-attr="right">Option 4</label>
  
  <label class="option" data-attr="right">Option 5</label>
</form>

Answer №3

Check out the functional demonstration on this link

$(document).ready(function() {
  $("input[type='radio']").on('click',function() {
    if($(this).attr('value')=="wrong"){
    $(this).next().css("background", "red");
   }else{
      $(this).next().css("background", "green");
  }
  });
});
.option {
  background: #eee;
  display: block;
  padding: 5px 10px 5px;
  color: #000;
  text-decoration: none;
  -moz-border-radius: 6px;
  -webkit-border-radius: 6px;
  -khtml-border-radius: 6px;
  border-radius: 6px;
  box-shadow: inset 0px 1px 3px rgba(0, 0, 0, 0.6);
  -moz-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.6);
  -webkit-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.6);
  text-shadow: 0px -1px 1px rgba(0, 0, 0, 0.25);
  border-bottom: 1px solid rgba(0, 0, 0, 0.25);
  position: relative;
  cursor: pointer;
  text-decoration: none;
  margin-bottom: 10px;
}
input[type="radio"] {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form3">
  <input type="radio" name="option" value="wrong" class="option1">
  <label class="option">Option 1</label>
  <input type="radio" name="option" value="wrong" class="option2">
  <label class="option">Option 2</label>
  <input type="radio" name="option" value="wrong" class="option3">
  <label class="option">Option 3</label>
  <input type="radio" name="option" value="right" class="option4">
  <label class="option">Option 4</label>
  <input type="radio" name="option" value="wrong" class="option5">
  <label class="option">Option 5</label>
</form>

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

Tips for adding content to several elements at once using jQuery

My HTML structure is as follows : <span class="section2 section4">hello</span> <span class="section1">World</span> <div class="tab" id="tab1"></div> <div class="tab" id="tab2"></div> <div class="tab" id= ...

The continual appearance of "No file found" persists when utilizing the $redirectRoute

My goal is to make one of the links on my website lead to another page within the site. Below is one of the two links found on my index.html page: <html ng-app="myApp"> . . . <body> <h1>My Home Page</h1> ...

Low-quality CSS Gradient Design

Hey everyone, Feel free to take a look at my preloader on this link: (Hit ESC as soon as the page loads to pause the website and focus on the loader) Upon closer inspection, you'll notice that there is an issue with the quality of the background l ...

The successful execution of an AJAX call is contingent upon the response echoed from PDO

I am seeking assistance to customize the success message in an ajax call based on the result of inserting data into a MySQL table. $.ajax({ data: dataString, type: 'POST', url: 'mypage.php', ...

Steps to retrieve data (token) from developer tools and incorporate it into a fetch Post request

Is there a simple way to extract data using dev tools and insert it into a fetch request? I am trying to make a POST request through the console, but I am struggling to correctly copy a token. I attempted to use querySelector but instead of finding the t ...

Having issues updating cookies with jQuery in ASP.NET framework

On my asp.net web page, I have implemented a search filter functionality using cookies. The filter consists of a checkbox list populated with various categories such as sports, music, and food. Using a jQuery onchange event, I capture the index and categor ...

What's causing the excessive amount of white space in my image?

Whenever I include a picture of myself on the page, it creates excessive white space at the bottom. I'm not sure why this happens, but removing the image eliminates the white space. I've attempted adjusting the margins and padding, as well as se ...

Adaptive website backdrop

I have created a unique background for my website design, which includes 3 slices labeled as div id top, middle, and bottom. You can view the design in this image. I am interested in making this background responsive. While I have come across examples of ...

Obtain the child's identification number and include it in the parent element as an ARIA

I need assistance with a JavaScript (or jQuery) function to dynamically add an 'aria-labelledby' attribute to parent <figure> elements based on the ID of the <figcaption>. I have multiple images and captions set up in <figure>&l ...

Collapse in Bootstrap without any Animation

How can I add animation to the Bootstrap Collapse feature on my website? I am using an icon from the Font Awesome library to trigger the collapse effect, but currently, it just pops up without any animation. What could be causing this issue? You can view ...

Adhesive side panel using Bootstrap 5

I've run into an issue while trying to make a side div sticky using Bootstrap 5. I applied the position-sticky class, but it doesn't seem to work as expected. Surprisingly, it works for the top div that I also want to stick. Adding fixed-top or s ...

HTML5's drag-and-drop feature, including nested targets, allows for intuitive and interactive user

I'm currently implementing HTML5 drag and drop functionality. I have a parent div that is droppable, and inside it, there is another child div that is also droppable. <div id="target-parent"> <div id="target-child"></div> </d ...

Attempting to load using ajax, Chrome and jquery-mobile will modify the location of the window through setting window.location.href

I'm encountering a challenge with my mobile application where I need to redirect users to the login page on a 401 ajax call. However, it seems that jQM is attempting to load this via AJAX when the request is sent. This solution works flawlessly for s ...

The combination of a modal box, checkbox, and cookie feature creates

I am trying to accomplish the following tasks: When the homepage loads, I want a modal box to appear Inside the modal box, there should be a form with a mandatory checkbox After checking the checkbox, submit the form and close the modal box to return to ...

What is the best way to update a targeted component in React when triggered by an event handler?

Your goal may seem straightforward, but getting a reference to a specific component using this is proving to be tricky. Here we have our App.js file: import React, { Component } from 'react'; import CoolBox from './coolBox.js'; import ...

When an element is appended, its image height may sometimes be mistakenly reported as

I am dynamically adding divs and I need to retrieve the height and width of an image. Based on this information, I have to apply CSS to the MB-Container class. For example: if the image is portrait orientation, set container width to 100%. If it's ...

What is the best approach for transmitting data to the post method of Node.js using AJAX/jQuery?

A UDP server I have is set up to respond with a different message each time it receives a message. When I hard code the message into the variable "message," everything works fine. However, I want the client to be able to manually type in a message, and t ...

Tips for preserving scroll location on Angular components (not the window) when navigating

My current layout setup is like this: https://i.sstatic.net/hOTbe.png In essence <navbar/> <router-outlet/> The issue I'm facing is that the router-outlet has overflow: scroll, making it scrollable (just the outlet section, not the ent ...

What is the correct way to handle BINDing both before and after POPSTATE events when using AJAX?

When dealing with slow AJAX processes, displaying a "loading..." message to the user was deemed beneficial. I have experience using history.pushState and history.popState, but my loading image does not show up when performing actual AJAX requests upon pres ...

An error occurred while attempting to save a new entry using the New Entry Form in DataTable, stating that the variable "

I have encountered an issue with a table that includes a bootstrap modal containing a form. After filling out the form and saving the data or closing the modal, I want to refresh the table data. However, I am receiving the following error: TypeError: c i ...