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

What could be causing the compatibility issue between fr units and grid-template-rows in CSS grid?

I'm having trouble getting the row height to change using fr units in my grid-template-rows. It seems to work fine with other units like pixels, but not with fr. I find it confusing that the fr units work perfectly fine with grid-template-columns, so ...

Demonstration of using .queue() and .dequeue() in relation to $.queue() and $.dequeue()

I successfully completed an animation using animate(), queue(), and dequeue(). However, I recently discovered that jQuery also offers jquery.queue() or $.queue() and jquery.dequeue() or $.dequeue(). Can anyone assist me in understanding these new terms w ...

Looking to display a submenu next to its parent element

I have a list that is not in order: <ul> <li>Parent-1 <ul> <li>Child-1</li> <li>Child-2</li> <li>Child-3</li> </ul> </li> <li>Parent-2 <ul> <li>Ch ...

The z-index overlapping problem in webkit browsers is a result of Angular 7 animations

I have implemented staggered animations in my Angular 7 application to bring elements to life upon page load. However, I am facing a strange z-index problem with one of my components. Here is the animation code: @Component({ selector: 'track-page& ...

Is there a way to convert the structure of HTML/CSS into JSON format?

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .collapsible { background-color: #004c97; color: white; cursor: pointer; padding: 18px; width: 100%; border: none; text ...

Ways to prevent scrolling in Angular 6 when no content is available

I am developing an angular 6 application where I have scrollable divs containing: HTML: <button class="lefty paddle" id="left-button"> PREVIOUS </button> <div class="container"> <div class="inner" style="background:red">< ...

Disabled radio buttons are appearing as if they have been chosen

While working on customizing the styles of radio buttons in a form, I encountered an issue where disabled radio buttons appeared selected even though they were supposed to show as disabled. Here is the code snippet that I used: input ::-ms-clear { ...

Issues with the Textarea StartsWith Function Being Unresponsive

Attempting to use the startsWith function on a textarea, but it seems like there may be an error in my code. Since I am not well-versed in Javascript, please forgive any obvious mistakes. I did try to implement what made sense to me... View the Fiddle here ...

Exploring the process of querying two tables simultaneously in MySQL using PHP

I currently have a search box in my PHP file that only searches from the "countries" table. However, I also have another table called "continent" and I would like the search box to retrieve results from both the "countries" and "continent" tables. Here is ...

Python Issue with BeautifulSoup: find_all() returning incorrect list of elements

I am currently using Python 2.7.3 and the bs.version I have is 4.4.1 However, when running this code snippet: from bs4 import BeautifulSoup # parsing html = """ <html> <head id="Head1"><title>Title</title></head> <body&g ...

Autocomplete with Jquery UI: navigate to the following input field once a response is received

My goal is to select the two input boxes after the autocomplete box. However, I am facing an issue where I cannot do so. <script> $('.autocomplete').die('focus').live('focus', function(){ $(this).autocomplete({ ...

What is the method for deactivating a hyperlink with CSS?

Within my wordpress page, there is a specific link present. This particular link belongs to a class. Is it viable to deactivate this link solely through the use of CSS? <a class="select-slot__serviceStaffOrLocationButton___5GUjl"><i class="mater ...

Utilizing jQuery for cloning elements

I need to add functionality for adding and deleting rows in multiple tables on my website. Currently, I am doing this by directly inserting HTML code using jQuery, but it has become inefficient due to the number of tables I have. I am considering creating ...

Modal window displaying MVC 4 partial view

I've been attempting to display a partial view using a popup, but it's not working. The controller method is also not being triggered. Here's my code: Script:- $(document).ready(function () { $.ajaxSetup({ cache: false }); ...

resolving table refresh problem with the use of ajax, JQuery, and JSON

I have populated a set of records in HTML table format. Each row includes an anchor tag with a trash-can image at the last column. When this image is clicked, I want to delete the respective row and refresh the table with updated data. My approach involves ...

Revitalizing JSP Table with jQuery & Ajax: The Ultimate Guide

I'm a beginner in the field of web development. Currently, I have developed an application using Spring MVC and JSP. However, when my page reloads after submitting a form, which is not the desired behavior. I would like to implement jQuery and Ajax ...

How can we add a class to a radio button using jQuery when it is checked, and remove the class when it

I'm looking for help with using jQuery to toggle between two radio buttons and display different divs based on the selection. jQuery(document).ready(function($) { if ($('#user_personal').is(':checked')) { $('.user_co ...

Incorporating jQuery to Load Content into a DIV while preserving the original JavaScript

I am attempting to implement the following <script> $(document).ready( function() { var data = 'testing' $("#about").on("click", function() { $("#main-content").load("/about.html"); ...

Handling mousewheel events for child elements and their parent element

I developed a custom jQuery plugin that replaces the default scrollbar with my own, managing mousewheel and bar dragging events. The issue arises when I place content containing my custom scrollbar within another content also using my scrollbar. When I sc ...

The POST request is coming back as null, even though it includes both the name and

Having issues with a login PHP code where the post method is returning an empty string. Here is my HTML code: <form action="iniSesion.php" method="post"> <div class="form-group"> <input type="email" name="email_" class ...