Steps for applying background color to div based on radio button selection:

Is it possible to change the background color of a div when a radio button is checked? I want the selected radio button to make the whole div appear as if it is selected.

If the radio button inside .pricing-option.one is checked, then .pricing-option.one should change its background color. The same rule applies for .pricing-option.two and all others.

This is what I am trying to achieve:

https://i.sstatic.net/jvdHa.png

I need help understanding how to implement this. Can anyone provide assistance?

This is the relevant code snippet:

<div class="visible-xs mobile-pricing-table clearfix">
    <div class="col-xs-4 pricing-option one text-center">
        <div class="ticket-quantity">
            <h2>50</h2>
            <p>Lottery Tickets</p>
        </div>
        <div class="winning-chances">
            <h2>17%</h2>
            <p>Winning Chances</p>
        </div>
        <div class="price">
            <strike>€114.99</strike>
            <h2>€14.99</h2>
            <p>You save 100€</p>
        </div>
        <div class="offer-selection">
            <input type="radio" name="optionsRadios" id="optionsRadios4" value="option4">
            <label for="optionsRadios4"></label>
        </div>
    </div>

    <div class="col-xs-4 pricing-option two text-center">
        <div class="ticket-quantity">
            <h2>200</h2>
            <p>Lottery Tickets</p>
        </div>
        <div class="winning-chances">
            <h2>68%</h2>
            <p>Winning Chances</p>
        </div>
        <div class="price">
            <strike>€126.40</strike>
            <h2>€26.40</h2>
            <p>You save 100€</p>
        </div>
        <div class="offer-selection">
            <input type="radio" name="optionsRadios" id="optionsRadios5" value="option5">
            <label for="optionsRadios5"></label>
        </div>
    </div>

    <div class="col-xs-4 pricing-option three text-center">
        <div class="ticket-quantity">
            <h2>400</h2>
            <p>Lottery Tickets</p>
        </div>
        <div class="winning-chances">
            <h2>87%</h2>
            <p>Winning Chances</p>
        </div>
        <div class="price">
            <strike>€149.9</strike>
            <h2>€49.9</h2>
            <p>You save 100€</p>
        </div>
        <div class="offer-selection">
            <input type="radio" name="optionsRadios" id="optionsRadios6" value="option6">
            <label for="optionsRadios6"></label>
        </div>
    </div>
</div>

Answer №1

Utilize the empty <label> positioned right after the radio button to apply a background color using the selector: :checked + label

This method involves using position:relative + absolute, coordinates and z-index. It works if the column has no background, but if it does, all children will need relative positioning along with a positive z-index. In this scenario, the label does not require a z-index.

Try the demo snippet below by clicking on the radio button to see the background color change :)

.pricing-option {
  position:relative;/* this tells absolute children where it stands */
  }
:checked + label {
  position:absolute;
  /* coordinates to cover all sides of the relative parent container */
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:lightblue;
  z-index:-1;/* place it beneath the container */
  }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

<div class="">
    <div class="col-xs-4 pricing-option one text-center">
        <div class="ticket-quantity">
            <h2>50</h2>
            <p>Lottery Tickets</p>
        </div>
        <div class="winning-chances">
            <h2>17%</h2>
            <p>Winning Chances</p>
        </div>
        <div class="price">
            <strike>€114.99</strike>
            <h2>€14.99</h2>
            <p>You save 100€</p>
        </div>
        <div class="offer-selection">
            <input type="radio" name="optionsRadios" id="optionsRadios4" value="option4">
            <label for="optionsRadios4"></label>
        </div>
    </div>

    <div class="col-xs-4 pricing-option two text-center">
        <div class="ticket-quantity">
            <h2>200</h2>
            <p>Lottery Tickets</p>
        </div>
        <div class="winning-chances">
            <h2>68%</h2>
            <p>Winning Chances</p>
        </div>
        <div class="price">
            <strike>€126.40</strike>
            <h2>€26.40</h2>
            <p>You save 100€</p>
        </div>
        <div class="offer-selection">
            <input type="radio" name="optionsRadios" id="optionsRadios5" value="option5">
            <label for="optionsRadios5"></label>
        </div>
    </div>

    <div class="col-xs-4 pricing-option three text-center">
        <div class="ticket-quantity">
            <h2>400</h2>
            <p>Lottery Tickets</p>
        </div>
        <div class="winning-chances">
            <h2>87%</h2>
            <p>Winning Chances</p>
        </div>
        <div class="price">
            <strike>€149.9</strike>
            <h2>€49.9</h2>
            <p>You save 100€</p>
        </div>
        <div class="offer-selection">
            <input type="radio" name="optionsRadios" id="optionsRadios6" value="option6">
            <label for="optionsRadios6"></label>
        </div>
    </div>
</div>


edit

As <label> is being used for another purpose, let's add an empty tag to achieve the same effect without JavaScript:

.pricing-option {
  position:relative;/* this tells absolute children where it stands */
  }
:checked ~ .bg {
  position:absolute;
  /* coordinates to reach each sides of the relative parent container */
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:lightblue;
  z-index:-1;/* put it underneath the container */
  }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

<div class="">
    <div class="col-xs-4 pricing-option one text-center">
        <div class="ticket-quantity">
            <h2>50</h2>
            <p>Lottery Tickets</p>
        </div>
        <div class="winning-chances">
            <h2>17%</h2>
            <p>Winning Chances</p>
        </div>
        <div class="price">
            <strike>€114.99</strike>
            <h2>€14.99</h2>
            <p>You save 100€</p>
        </div>
        <div class="offer-selection">
            <input type="radio" name="optionsRadios" id="optionsRadios4" value="option4">
            <label for="optionsRadios4"></label>
          <i class="bg"></i>
        </div>
    </div>

    <div class="col-xs-4 pricing-option two text-center">
        <div class="ticket-quantity">
            <h2>200</h2>
            <p>Lottery Tickets</p>
        </div>
        <div class="winning-chances">
            <h2>68%</h2>
            <p>Winning Chances</p>
        </div>
        <div class="price">
            <strike>€126.40</strike>
            <h2>€26.40</h2>
            <p>You save 100€</p>
        </div>
        <div class="offer-selection">
            <input type="radio" name="optionsRadios" id="optionsRadios5" value="option5">
            <label for="optionsRadios5"></label>
          <i class="bg"></i>
        </div>
    </div>

    <div class="col-xs-4 pricing-option three text-center">
        <div class="ticket-quantity">
            <h2>400</h2>
            <p>Lottery Tickets</p>
        </div>
        <div class="winning-chances">
            <h2>87%</h2>
            <p>Winning Chances</p>
        </div>
        <div class="price">
            <strike>€149.9</strike>
            <h2>€49.9</h2>
            <p>You save 100€</p>
        </div>
        <div class="offer-selection">
            <input type="radio" name="optionsRadios" id="optionsRadios6" value="option6">
            <label for="optionsRadios6"></label>
          <i class="bg"></i>
        </div>
    </div>
</div>

Answer №2

Could you please clarify if my understanding is correct? It seems like you are attempting to change the color of a table row when a child radio button is clicked. What purpose do the div elements serve in this context? I made some slight modifications to JG Estevez's JavaScript code and it successfully achieved the desired result.

$('input:radio').change(function(){
  var selectedElement=$(this);
  $('tr').each(function(){
    $(this).css('background','#fff');
  });
  selectedElement.closest('tr').css('background','coral');
});

View the highlighted first row here

Answer №3

I came up with a solution that could work for your issue. Although I haven't tried it myself, the concept is pretty simple. When you select a radio button, all container backgrounds will change to the non-selected color, and then only the selected radio button's container will change to the selected background color.

 $('input:radio').change(
          var chosenElement=$(this);
          $('.pricing-option').each(function(){
            $(this).css('background','yournonselectedshade');
          });
          chosenElement.closest('.pricing-option').css('background','yourdesiredcolor');
        ); 

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

Building nested routes in a protected path using react-router version 6

At the moment, I am utilizing react-router-dom version 6.1.1 and I have a private route in use. Typically, within this private route, I include other routes to maintain my Sidebar. This is how my code appears: // App.tsx const RequireAuth: React.FC<P ...

Creating a custom validation message for a single element using jQuery Validate

Is there a way to customize the validation message when utilizing jQuery validation for a single element? In this scenario, I am attempting to validate the select list with the ID "DestinationId" when a button is clicked. $(".process").click(function () ...

Fetching Results from Promise

Repeatedly, this question has been asked in various forms but I still do not understand: I have a resolved promise with a value. When I console.log this object, everything appears to be functioning correctly. I can see exactly what I want to see. My setu ...

Difficulty with displaying or concealing Javascript code

After stumbling upon this script online, I discovered that it is designed to show/hide text boxes and labels. However, any alterations to the code seem to disrupt its functionality. For instance, changing divpassword will cause it to stop functioning altog ...

Revamp the UI Framework's CSS to accommodate the latest Web Components

I've implemented Grommet as the UI Framework for my React page. However, I encountered a situation where certain web components, like a web chat control, are not covered by Grommet's CSS. What is the simplest way to style these additional web com ...

Traverse through a range of numbers using the object.keys method

I need to iterate through a list of objects using Object.keys, but I only want to loop through items between numbers 3 and 5. How can I achieve this while skipping the rest of the list? const obj = { '#1 List title': [{ title: ' ...

Is it possible to print a document without it ever showing on the screen

I am developing a feature on my page that allows users to print. The challenge I am facing is that when the user clicks print, I want to generate a new page in the background called "Printable.aspx" and only display the print dialog for it without disrupti ...

Ways to initiate SVG animations using Angular Component functions?

I am currently working on a project where I want to incorporate an animation that reflects the sorting process of an array of numbers. However, despite successfully sorting the numbers in the array, I am facing challenges with triggering the animations. I ...

Is there a way to prevent external scripts from loading within an iframe?

When dynamically creating iframes, is it possible to prevent scripts from running that do not originate from the iframe's origin using JavaScript or jQuery? For example, let's say my page loads an iframe from example.com with the following conten ...

Explore how Vue 2.1 allows for the dynamic updating of dropdown options based on selections made in another dropdown

Currently, I have a Vue v.2 form set up with an address section that includes a State dropdown. My goal is to make the State dropdown automatically populate based on the city selected. For example, if a user chooses 'Atlanta' as the city, 'G ...

Conceal a particular object from view by selecting it from the menu

I want to hide a specific element when the burger button is clicked. (See CaptureElementNoDisplay.PNG for the element to hide) When I click the burger button again to close the menu, I want the hidden item to be displayed once more. I've successfull ...

Addressing the issue of audio files not being cached by IOS web browsers

I am currently developing a language learning website where users can listen to audio by clicking on objects. Many of the site's users are in remote areas with slow Internet connections, so I need to cache the audio files before each activity loads to ...

Error occurs when there is an issue with the value in the Ace editor and the

When using the ace editor to modify JavaScript scripts, an error occurs when attempting to assign a variable with the value of "<script>" + jse.getValue() + "</script>";. I have tried adding .toString() and jse.value() without success. Any ass ...

Sending information into MySQL using NodeJS with the help of Postman

As a newcomer in the field, I am exploring how to combine MySQL with nodeJS for integrating projects into WordPress. app.post('/users/add', (req, res) => { id = req.body.id, firstname = req.body.firstname, surname = req.body.surname ...

My Node.js update query is not retrieving the correct values

Having some trouble with an update query on my nodejs server. It seems to be functioning properly, but I'm only getting the ID and not the values. Can't seem to figure out how to fix it. Any help would be appreciated! Server-side: app.post(&apo ...

The Angular Material FAB Speed Dial feature is causing a slight offset within the Toolbar

Attempting to incorporate design examples from the angular material site, I am utilizing Angular Material 1.0.0RC5. I am aiming to position the FAB Speedial within the Toolbar, similar to the example demonstrated on their site: https://material.angularjs. ...

Changing Scroll-bar Colors in JavaFX TableView Using Java

I modified the style of my TableViews programmatically with the following code- tableView.setStyle("-fx-base : #333333; -fx-background-color : gray"); Now I am looking to change the color of the scroll bar using the same method. I prefer not to add a ...

Encountered an error "Not Found" when attempting to establish an AJAX connection between Javascript and Rails

I'm having an issue with a simple Rails controller method. When I call it from JavaScript as an AJAX method, I get the error message "Not Found" in the JavaScript error log, even though the method works fine when accessed directly in the browser. What ...

Are YUI CSS Fonts affected by %-based sizing when used in nested elements?

When utilizing YUI's CSS system, font-sizes are defined in percentages instead of pixels to ensure a consistent font size across different browsers. However, if you have elements with specified font sizes, any nested elements with font sizes set will ...

Enhance your images with Jquery thumbnail zoom feature

I am in the process of creating color swatches for clothing items, using them as a reference point. http://jquery.malsup.com/cycle/pager7.html Take a look at the thumbnails on the webpage mentioned above. My goal is to display these thumbnails without re ...