Modify the appearance of a card upon radio button selection

Can someone help me figure out how to change the background color of my card element when a radio button is selected?

<div class="col-6 col-md-3 mt-4 text-center my-auto">
            <label for="'.$abreviation.'">
                <div class="card card-block d-flex">
                    <div class="card-body align-items-center d-flex justify-content-center">
                        <input type="radio" id="'.$abreviation.'" name="tri" value="'.$abreviation.'" class="check-on" /> '.$tri.'
                    </div>
                </div>
            </label>
        </div>

Is there a way to do this using only CSS, or do I need to use JavaScript or jQuery? I attempted it myself, but all the cards end up with a red background instead of just the selected one.


    $(document).ready(function(){

        $(".check-on").click(function(){

          $('.check-on').parent().parent().addClass('backgroundCard') 

        });

    });

Thank you in advance for your assistance.

Answer №1

  1. When the input tag is nested within a label tag, there is no need to associate a label with it using the for attribute.
  2. The styling of the card can be achieved without the use of JavaScript. Simply position the card adjacent to the input field, conceal the input by applying the d-none class, and utilize the adjacent element combinator.

Try interacting with the cards, they now function like radio buttons.

input[type="radio"]:checked + .card {
  background: #f1f1f1;
}
<div class="col-6 col-md-3 mt-4 text-center my-auto">
    <label>
        <input type="radio" name="tri" value="'.$abreviation.'" class="d-none" />
        <div class="card card-block d-flex">
            <div class="card-body align-items-center d-flex justify-content-center">
                '.$tri.'
            </div>
        </div>
    </label>
</div>

<div class="col-6 col-md-3 mt-4 text-center my-auto">
    <label>
        <input type="radio" name="tri" value="'.$abreviation2.'" class="d-none" /> 
        <div class="card card-block d-flex">
            <div class="card-body align-items-center d-flex justify-content-center">
                '.$tri.'
            </div>
        </div>
    </label>
</div>

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f1939e9e858285839081b1c4dfc1dfc3">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

Answer №2

$(document).ready(function(){
    $(".check-on").click(function(){
          $(this).parent().parent().addClass('backgroundCard')
    });
});

After clicking on the element with class "check-on", only keep focus on that specific element using the this selector instead of selecting all elements by class again.

Answer №3

You have the ability to toggle classes using the on change event.

If you are dealing with multiple radio button groups, you can extract the name attribute of those radios and use it to remove the class from the appropriate cards:

$(this).attr('name');

$('.check-on').on('change', function() {
  let radioName = $(this).attr('name');
  $(`.check-on[name=${radioName}]`).closest('.card.backgroundCard').removeClass('backgroundCard');
  $(this).closest('.card').addClass('backgroundCard');
});
.card.backgroundCard {
  background: #f1f1f1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfbdb0b0abacabadbeaf9feaf1eff1ed">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<div class="col-6 col-md-3 mt-4 text-center my-auto">
    <label for="'.$abreviation.'">
        <div class="card card-block d-flex">
            <div class="card-body align-items-center d-flex justify-content-center">
                <input type="radio" id="'.$abreviation.'" name="tri" value="'.$abreviation.'" class="check-on" /> '.$tri.'
            </div>
        </div>
    </label>
</div>

<div class="col-6 col-md-3 mt-4 text-center my-auto">
    <label for="'.$abreviation2.'">
        <div class="card card-block d-flex">
            <div class="card-body align-items-center d-flex justify-content-center">
                <input type="radio" id="'.$abreviation2.'" name="tri" value="'.$abreviation2.'" class="check-on" /> '.$tri.'
            </div>
        </div>
    </label>
</div>

Answer №4

You can achieve this without the need for Javascript or jQuery, just with a simple CSS solution.

/* This CSS snippet is used for normalizing styles. It can be skipped if not needed. */
*, *:before, *:after {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.new {
  padding: 50px;
}

.form-group {
  display: block;
  margin-bottom: 15px;
}

.form-group input {
  padding: 0;
  height: initial;
  width: initial;
  margin-bottom: 0;
  display: none;
  cursor: pointer;
}

.form-group label {
  position: relative;
  cursor: pointer;
  display: inline-block;
  padding: 10px;
}

.form-group label:before {
  content: '';
    position: absolute;
    -webkit-appearance: none;
    background-color: transparent;
    border: 2px solid #0079bf;
    display: inline-block;
    vertical-align: middle;
    cursor: pointer;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
}

.form-group input:checked + label:after {
  content: '';
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #0079bf;
    z-index: -1;
  
}
<div class="new">
  <form>
    <div class="form-group">
      <input type="radio" id="$tri-1" name="radio">
      <label for="$tri-1">$tri-1</label>
    </div>
    <div class="form-group">
      <input type="radio" id="$tri-2" name="radio">
      <label for="$tri-2">$tri-2</label>
    </div>
    <div class="form-group">
      <input type="radio" id="$tri-3" name="radio">
      <label for="$tri-3">$tri-3</label>
    </div>
  </form>
</div>

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

Next-auth custom authentication provider with unique backend

I am currently experiencing an issue with sessions while using auth authentication. My next-auth version is 4.0.0-beta.4 (also tried beta.7 with the same results). My backend utilizes a custom JWT token system that returns an object containing an access t ...

Accessing office documents such as XLS and PPT files directly within the browser window using Internet Explorer 7.0

Currently using XP, IE 7.0, Office 2010, and operating within a company INTRAnet environment. I have created a HomePage in Word and saved it as HTML, including links to other Office files. Despite my attempts, I am unable to get these office files to ope ...

Unexpected issue with controller functionality following modification to URL

Summary: I am facing an issue with my controller triggering jQuery in my AngularJS web page. The controller successfully fades out a play button and an image on the initial page, but fails to work on subsequent pages when the URL changes. I suspect that t ...

What is the best way to extract data from various HTML files using RVEST and save it into an Excel spreadsheet?

I am struggling to find a solution for my current problem as I am not fluent in R. My challenge is working with 800 html files and accessing all the h2 elements within each file. Currently, I have managed to do this with individual website URLs using the ...

Is there a way to troubleshoot the "module not found error" that keeps popping up when I attempt to execute the code following a smooth installation of sqlite3?

Initially, I successfully installed the sqlite3 module but encountered errors like "module not found". However, upon attempting to reinstall sqlite3 (npm install sqlite3), more errors surfaced that required thorough post editing. The output is as follows: ...

Explore the versatility of jQuery by utilizing multiple objects in your POST and GET requests to PHP for enhanced

I am trying to send multiple arrays to a PHP page using jQuery and retrieve results, but I am encountering an issue where the array values are not being properly passed to the PHP page. Notice: Undefined index: $name Notice: Undefined index: $type Notice ...

Arrange the data in the table to ensure that it is organized neatly into the appropriate columns

I am currently working on a project that involves creating a table to display user answers for purchased tickets under the corresponding questions. If a question has not been answered, I want to show a dash symbol instead. However, I am encountering an is ...

Unlocking Discord Account Information through OAuth2

Currently, I am in the process of developing a moderation bot for Discord. I am working on implementing a paid plan and as part of that, I require users to log in with their Discord account using OAuth2. This allows me to retrieve user data and identify wh ...

"Learn the art of combining an ajax request with a captivating background animation at the same time

I'm currently working with the following code snippet: $('#contentSites').fadeOut(200, function() { // Animation complete $.get("my_account_content.php?q=" + content, function(data){ $("div#contentSit ...

Fetching image for jmapping AJAX request

Struggling to incorporate a loading image when making an ajax call using the jquery jmapping plugin to update categories on a map. While I typically work with PHP, I've put together this script below and it's all I could come up with. Any assista ...

Guide to selecting a date using JavaScript in Selenium with Ruby

I'm having some trouble selecting a date from a date picker field using JavaScript in Selenium WebDriver. I've attempted the code below, which does navigate to the date window successfully, but I can't figure out how to execute the JavaScrip ...

Using jQuery to fill input fields automatically with a mouse click rather than using the keyboard

I found a solution that works great for my needs here $("#EmailAddress").keyup(function(){ $("#Username").val(this.value); }); Even though this solution works perfectly when entering values with the keyboard, it doesn't seem to function properly ...

Tips for managing an event using the bxSlider callback API

I am currently using bxSlider to create a slideshow on my website. However, I now want to implement a manually controlled slideshow that also displays text content related to each image below the slideshow: Here is the code I have so far: <!--SlideSho ...

Reloading a Nuxt.js page triggers the fetch function

I'm facing an issue with nuxt.js fetch(). Whenever I reload the page, it does not fetch the data again. It only fetches if I come from a router link. How can I force it to actually refetch the data from my API? export default { async fetch() { ...

Creating dynamic web pages using Smarty templating engine to render HTML

I'm attempting to display my unprocessed HTML content using Smarty. {if !empty($brand.description)} {$brand.description} {/if} Although the initial text includes spaces and line breaks, when viewed, the HTML appears as plain text. I also experimen ...

JavaScript Issue: Unable to Update or Delete Table Row Data

Presently, I am involved in developing a project titled : Tennis Club Management using a blend of Javascript, HTML, CSS, and Bootstrap. This project encompasses several HTML pages and a JS file such as index.html, profile.html, manageFees.html, index.js, e ...

The React/Redux bundle.js file is overly large and bloated

I am currently working on a React project, and the bundle.js file generated by Webpack is quite large at 6.3Mb. I am looking for ways to reduce this size to less than 2.0Mb (though 2Mb would still be acceptable). The full source code can be found on Github ...

Struggling with hashtags and ampersands in Angular when making an HTTP request

Dealing with Special Characters # and & in Angular's http.get() Request URL Take a look at my code first. Angular Service let versionsearch = "&"; let strweeksearch = "%23"; this.http.get(this.apiUrl + 'GetVersionInfo?vehicleVersion=' + v ...

What could be causing my wrapper div to not clear properly?

Something seems off with my wrapper div as it's not completely wrapping the children divs vertically. I made sure to clear both of the contained divs but it doesn't seem to be working properly. Any insight on why this might be happening? Check o ...

Executing webpack with specific settings in Node.js

In my current package.json file, I have a script defined as follows: "build": "webpack --inline --colors --progress --display-error-details --display-cached", Additionally, there is a webpack.config.js file located at the root of my repository. To strea ...