Reputation: 5493
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
Reputation: 206508
.each()
$(this).closest('selector')
to target the closest selector.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:
:checked
pseudo~
/* 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