Hard Coded
Hard Coded

Reputation: 70

jQuery - How can I add a class for a single div containing a checkbox relative to the checked box?

Here is the HTML:

<ul>
  <li>
    <div class="checkbox-wrap">
      <p>Check this: 
      <input type="checkbox" />
      </p>
    </div>
  </li>
  <li>
    <div class="checkbox-wrap">
      <p>Check this: 
      <input type="checkbox" />
      </p>
    </div>
  </li>
  <li>
    <div class="checkbox-wrap">
      <p>Check this: 
      <input type="checkbox" />
      </p>
    </div>
  </li>
</ul>

The jQuery:

$this('input:checkbox').change(function(){
    if($(this).is(":checked")) {
        $('div.checkbox-wrap').addClass("active-checkbox");
    } else {
        $('div.checkbox-wrap').removeClass("active-checkbox");
    }
});

When you check a checkbox the class "active-checkbox" is being added to the whole 3 divs. Is there any way to add the class for a single div and not for the whole 3 divs without using ID or custom class names ?

Thanks

Upvotes: 1

Views: 127

Answers (5)

Adil
Adil

Reputation: 148160

You have wrongly put $this('input:checkbox') instead of $('input:checkbox'), you can use closest() to find the first occurance of selector in up in ancestor hierarchy.

Live Demo

$('input:checkbox').change(function(){       
    if($(this).is(":checked")) {
        $(this).closest('div.checkbox-wrap').addClass("active-checkbox");
    } else {
        $(this).closest('div.checkbox-wrap').removeClass("active-checkbox");
    }
});​

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337656

You need to use closest to find the nearest .checkbox-wrap element:

$('input:checkbox').change(function() {
    var $checkbox = $(this);
    if ($checkbox.is(":checked")) {
        $checkbox.closest('div.checkbox-wrap').addClass("active-checkbox");
    } else {
        $checkbox.closest('div.checkbox-wrap').removeClass("active-checkbox");
    }
});

More information on closest()

Also, I assume $this at the start is an aliased version of jQuery, and not a typo?

Upvotes: 1

Sergii
Sergii

Reputation: 1320

$this('input:checkbox').change(function(){
   $(this).parents('div.checkbox-wrap').toggleClass("active-checkbox", $(this).is(":checked"));
});

Upvotes: 0

Usman
Usman

Reputation: 3278

you can use :eq() Selector to do this as

$(".checkbox-wrap:eq(0)").addClass("active-checkbox");

Check This out

Upvotes: 0

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50752

you can use nth-child selector

Upvotes: 1

Related Questions