Search code examples
jquerycssinputradio-button

How to add/remove class to parent div according to input radio selection using jQuery?


the below code shows 4 radio buttons that are hidden by default using the display:none property in CSS. However, I select them using the "label" tag. I also have a div wrapping everything.

I want to know how can I add/remove a class to this "div" tag if the contained radio box is selected.

So if I select a radio, the parent div will get a class, and if another radio is selected, the class is removed from this div and added to the parent div of the radio selected.

<div class="plan">
   <h3 class="division-one">Division One<span>€2</span></h3>
   <div><label for="23">1 month</label><input type="radio" name="membershipPlanSID" value="23" id="23" /></div>
   <div><label for="24">3 months</label><input type="radio" name="membershipPlanSID" value="24" id="24" /></div>
   <div><label for="25">6 months</label><input type="radio" name="membershipPlanSID" value="25" id="25" /></div>
   <div><label for="26">12 months</label><input type="radio" name="membershipPlanSID" value="26" id="26" /></div>
   <input type="hidden" name="returnBackUri" value="{$returnBackUri}" />
   <input class="signup" type="submit" value="[[Sign Up:raw]]" />
</div>

I tried something like this, but with no success:

$('input:radio').click(function() {
if($(this).is(':checked')) {
    $(this).parent().addClass('label-selected');
} else {
    $(this).parent().removeClass('label-selected');
}
});

Doing this, the class is never removed, despite the "else".

Thanks all in advance, Arky

EDIT: Thanks a lot guys for the very fast answers! Amazing community here :)


Solution

  • Problem

    Remember that a radio input element gets "unchecked" only when one of its counterparts is clicked. Unlike a checkbox input element, clicking a second time on a radio input does not clear its value.

    In your example, on the first click you are successfully adding the class to the parent div since the radio input is indeed :checked, but on the second click on the same radio input, that element remains :checked and therefore the parent's class is not removed.

    Solution

    Onclick of a radio input element, remove the class from all div elements except the immediate parent.

    For example:

     $('.plan :radio').on('click', function() {
         var parent_div = $(this).parent().addClass('label-selected');
         $('.plan').find('div').not(parent_div).removeClass('label-selected');
     });