Reputation: 70
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
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.
$('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
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
Reputation: 1320
$this('input:checkbox').change(function(){
$(this).parents('div.checkbox-wrap').toggleClass("active-checkbox", $(this).is(":checked"));
});
Upvotes: 0