-2

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>
AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43
JGeer
  • 1,768
  • 1
  • 31
  • 75
  • "also the ones that are not checked" - and how does `$('div.checkbox.product-option')` signify only the checked elements? – nicael Jun 06 '16 at 14:45

3 Answers3

5

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");
});
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
2

You can try .closest instead.

You are passing selector, hence its applying changes to all element that satisfies it. Try to make it relative to this

$(this).closest('div.checkbox.product-option').addClass("selected"); 

You can even use .parent():

$(this).parent().addClass("selected"); 

You can refer following post for more information: Difference between jQuery parent(), parents() and closest() functions

Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79
0

Instead of $('div.checkbox.product-option').addClass("selected"); which will select all the elements with that class just use this and find the checkboxes closest ancestor with that class.

jQuery(".checkbox-row").change(function() {
    if($(this).is(':checked')) 
        $(this).closest('div.checkbox.product-option').addClass("selected"); 
    else 
        $(this).closest('div.checkbox.product-option').removeClass("selected");
});
AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43