Alexander Hein Alexander Hein - 3 months ago 38
jQuery Question

Jquery: Add class to container if radio button is checked

How do I add the class

active
to the element
payment--method
if the inner radio button is checked?



.method--description{
display: none;
}

.payment--method.active .method--description{
display: block;
}

<div class="payment--method">

<div class="method--input">
<input type="radio" name="payment" value="1" id="payment_option1" checked="checked">
</div>

<div class="method--label">
<label for="payment_option1">Option 1</label>
</div>

<div class="method--description">
Option 1 description
</div>

</div>

<div class="payment--method">

<div class="method--input">
<input type="radio" name="payment" value="2" id="payment_option2">
</div>

<div class="method--label">
<label for="payment_option2">Option 2</label>
</div>

<div class="method--description">
Option 2 description
</div>

</div>




Answer

Please check below snippet.

$(document).ready(function(){
  makeActive();
  $("input[type='radio']").on("change",function(){
    makeActive();
  });
});
function makeActive(){
  $("input[type='radio']").each(function(){
      if($(this).prop("checked")){
        $(this).closest('.payment--method').addClass("active");
      }else{
        $(this).closest('.payment--method').removeClass("active");
      }
    });
}
.method--description{
  display: none;
}

.payment--method.active .method--description{
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="payment--method">

  <div class="method--input">
    <input type="radio" name="payment" value="1" id="payment_option1" checked="checked">
  </div>

  <div class="method--label">
    <label for="payment_option1">Option 1</label>
  </div>

  <div class="method--description">
    Option 1 description
  </div>

</div>

<div class="payment--method">

  <div class="method--input">
    <input type="radio" name="payment" value="2" id="payment_option2">
  </div>

  <div class="method--label">
    <label for="payment_option2">Option 2</label>
  </div>

  <div class="method--description">
    Option 2 description
  </div>

</div>