Cray
Cray

Reputation: 5493

jQuery: Add class if list item has checked radio button inside

I want to add an own class if a list item has an active radio button inside of it.

I tried this code to add a class but I guess there is an error in it:

$('input').change(function() {
  var check = $('.wc_payment_method').map(function(e) {
    return $(this).find('input[type="radio"]').is(':checked')
  }).get()

  $('.wc_payment_method').addClass('active');
})
.wc_payment_method {padding: 10rem;}
.active {background-color: #eee;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<ul>
  <li class="wc_payment_method payment_method_paypal">
    <input id="payment_method_paypal" type="radio" class="input-radio" name="payment_method" value="paypal">
    <label for="payment_method_paypal">PayPal</label>
  </li>

  <li class="wc_payment_method payment_method_creditcard">
    <input id="payment_method_creditcard" type="radio" class="input-radio" name="payment_method" value="creditcard">
    <label for="payment_method_creditcard">Credit card</label>
  </li>
</ul>

Upvotes: 4

Views: 544

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206508

  • Loop your inputs using .each()
  • go for $(this).closest('selector') to target the closest selector
  • use .toggleClass('className', Boolean) to toggle the class.

const $inp = $('[name="payment_method"]');

$inp.on("change", function() {
  $inp.each(function() {
    $(this).closest('.wc_payment_method').toggleClass('active', this.checked);
  });
});
.active { background: gold; }
<ul>
  <li class="wc_payment_method payment_method_paypal">
    <input id="payment_method_paypal" type="radio" class="input-radio" name="payment_method" value="paypal">
    <label for="payment_method_paypal">PayPal</label>
  </li>

  <li class="wc_payment_method payment_method_creditcard">
    <input id="payment_method_creditcard" type="radio" class="input-radio" name="payment_method" value="creditcard">
    <label for="payment_method_creditcard">Credit card</label>
  </li>
</ul>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

or don't use JavaScript at all:

  • Use the :checked pseudo
  • Target the sibling Label element General Sibling Combinator selector ~

/* Style the adjacent LABEL instead */
.input-radio:checked ~ label {
  background: gold;
}
<ul>
  <li class="wc_payment_method payment_method_paypal">
    <input id="payment_method_paypal" type="radio" class="input-radio" name="payment_method" value="paypal">
    <label for="payment_method_paypal">PayPal</label>
  </li>

  <li class="wc_payment_method payment_method_creditcard">
    <input id="payment_method_creditcard" type="radio" class="input-radio" name="payment_method" value="creditcard">
    <label for="payment_method_creditcard">Credit card</label>
  </li>
</ul>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

Upvotes: 3

Related Questions