Henk Z Henk Z - 6 months ago 25
jQuery Question

JQuery add class if selected for each input

I currently use the following jQuery code to add a class if the input type checkbox is checked. But it adds the class to all elements even if they are not checked.

How can I solve this?

HTML:

<div class="checkbox product-option">
<label for="addon1">
<span class="product-option-text">
<input class="checkbox-row" type="checkbox" name="addons[1]" id="addon1" onclick="prodconfrecalcsummary()">
<span class="text">Text</span>
</span>
</label>
</div>

<div class="checkbox product-option">
<label for="addon2">
<span class="product-option-text">
<input class="checkbox-row" type="checkbox" name="addons[2]" id="addon1" onclick="prodconfrecalcsummary()">
<span class="text">Text</span>
</span>
</label>
</div>

<div class="checkbox product-option">
<label for="addon3">
<span class="product-option-text">
<input class="checkbox-row" type="checkbox" name="addons[3]" id="addon1" onclick="prodconfrecalcsummary()">
<span class="text">Text</span>
</span>
</label>
</div>


jQuery:

<script>
jQuery(".checkbox-row").change(function() {
if($(this).is(':checked'))
$('div.checkbox.product-option').addClass("selected");
else
$('div.checkbox.product-option').removeClass("selected");
});
</script>

Answer

product-option is the parent container of checkbox. To get the current product-option, you need to use .closest(".product-option") selector

jQuery(".checkbox-row").change(function() {
  if ($(this).is(':checked'))
    $(this).closest(".product-option").addClass("selected");
  else
    $(this).closest(".product-option").removeClass("selected");
});