$.fn.linkNestedCheckboxes = function () {
var childCheckboxes = $(this).find('input[type=checkbox] ~ ul li input[type=checkbox]');
childCheckboxes.change(function () {
var checked = $(this).attr('checked');
checked = checked || ($(this).closest('li').siblings('li').find('input:checked').length > 0)
childCheckboxes.parent().closest('ul').siblings('input[type=checkbox]').attr('checked', checked);
});
var parentCheckboxs = childCheckboxes.parent().closest('ul').siblings('input[type=checkbox]')
parentCheckboxs.change(function () {
$(this).siblings('ul').find('input[type=checkbox]').attr('checked', $(this).attr('checked'))
})
return $(this);
};
Example of use:
<script type="text/javascript">
$(document).ready(function () {
$('form').linkNestedCheckboxes();
});
</script>
<form>
<input type="checkbox" name="parent" />
<ul>
<li><input type="checkbox" name="child1" /></li>
<li><input type="checkbox" name="child2" /></li>
</ul>
</form>
The result of this is:
- When
parent
is checked/unchecked all the child checkboxes will be out into the same state - If nothing is checked & one of the children are then checked, the parent will be checked
- When the last child is unchecked the parent will be unchecked
What I'd like to know is:
- Have I just re-invented the wheel?
- If not, is there a more efficient way of doing this? The selectors above seem a bit convoluted.
- This works on my machine, but I haven't tested it beyond my limited requirements for one form, will this break anything other than my simplistic example HTML?