JQuery passing through parent and children
I have a nested unsorted list and I want to place a click event on the parent checkbox, so when it checks, it checks all the child checkboxes and vice versa. For some reason I can only get a selector to get all checkbox type inputs ... ive tried a variety or ways, this is one of them. any suggestions?
<ul id="parent">
<li>
<input type='checkbox'>first</input>
<ul>
<li><input type='checkbox'>child1</input>
</li>
<li><input type='checkbox'>child2</input>
</li>
</ul>
</li>
<li>
<input type='checkbox'>second</input>
<ul>
<li><input type='checkbox'>child1</input>
</li>
<li><input type='checkbox'>child2</input>
</li>
</ul>
</li>
</ul>
JQuery
$('#parent > li input[type=checkbox]').click(function() {
var parent = $(this);
if ($(parent).is(':checked')) {
$('li > input[type=checkbox]', parent).each(function() {
$(this).attr('checked', true);
});
}
else {
$('li > input[type=checkbox]', parent).each(function() {
$(this).attr('checked', false);
});
}
});
+2
source to share
1 answer
This should work:
You will first go back to LI and then search for checkboxes
$('#parent > li input[type=checkbox]').click(function() {
$(this).closest("li").find("ul li input[type=checkbox]").attr('checked', $(this).is(':checked'))
});
However, you might consider adding some class names. This way your code becomes more readable.
<li>
<input type='checkbox' class='category'>first</input>
<ul>
<li><input type='checkbox' class='subcategory'>child1</input>
</li>
<li><input type='checkbox' class='subcategory'>child2</input>
</li>
</ul>
</li>
Than your jQuery would look like:
$("#parent .category").click(function(){
$(this).closest("li").find(".subcategory").attr('checked', $(this).is(':checked'))
});
+6
source to share