Reputation: 5493
I want to add a class to a <li>
if it contains a checked radio button.
This is my current HTML structure:
<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>
And this is what I've tried so far:
<script>
jQuery(function ($) {
$(".wc_payment_method :checked").each(function() {
$(this).addClass("is-checked");
alert(this.id + " is checked");
});
});
</script>
The alert works. It shows the correct <li>
item with a checked radio button.
But there are two problems I couldn't solve.
is-checked
on page loadCould anybody push me in the right direction?
Upvotes: 0
Views: 91
Reputation: 782106
If you want classes to change when you check or uncheck the boxes, you need an event handler. The handler can check whether each LI contains a checked button.
$(".wc_payment_method :radio").click(function() {
$(".wc_payment_method").each(function() {
$(this).toggleClass("is-checked", $(this).find(":radio:checked").length > 0);
});
});
.is-checked {
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/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_credit">
<input id="payment_method_credit" type="radio" class="input-radio" name="payment_method" value="credit">
<label for="payment_method_paypal">Credit Card</label>
</li>
</ul>
Upvotes: 1
Reputation: 166
Your code add a class only to the input tags. To add a specific class on click event you must use $().click metod from jquery.
jQuery(function ($) {
function addClass() {
$(".wc_payment_method input:checked").each(function() {
$(this).closest('li').addClass('yourClass');
$(this).addClass("is-checked");
alert(this.id + " is checked");
});
}
addClass();
$(".wc_payment_method input").click(function(){
addClass();
});
});
<script
src="https://code.jquery.com/jquery-3.5.0.min.js"
integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="
crossorigin="anonymous"></script>
<ul>
<li class="wc_payment_method payment_method_paypal">
<input id="payment_method_paypal" type="radio" class="input-radio" checked name="payment_method" value="paypal">
<label for="payment_method_paypal">PayPal</label>
</li>
<li class="wc_payment_method payment_method_paypal1">
<input id="payment_method_paypal1" type="radio" class="input-radio" name="payment_method1" value="paypal2">
<label for="payment_method_paypal1">PayPal</label>
</li>
</ul>
Upvotes: 0