I have a nested unsorted list and I want to place a click event on the parent checkbox so when it is check it checks all the children checkboxes and vice versa. For some reason I can only get the selector to get all inputs of type check box... 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);
});
}
});