Parent and child flags
<div id="customerServices">
<input id="s9" type="checkbox" /> Parent element<br/>
<input id="s15" class="parent-s9" type="checkbox" /> Child element<br/>
<input id="s16" class="parent-s9" type="checkbox" /> Child element<br/>
<br/><br/><br/>
<input id="s10" type="checkbox" /> Parent element2<br/>
<input id="s151" class="parent-s10" type="checkbox" /> Child element2<br/>
<input id="s161" class="parent-s10" type="checkbox" /> Child element2<br/>
<br/><br/><br/>
<input id="s101" type="checkbox" /> Parent element3<br/>
<input id="s102" type="checkbox" /> Parent element4<br/>
</div>
There are checkboxes on the page. I need:
- Check all children if the parent checkbox is selected.
- Uncheck the box if all children are not checked.
- Check the parent if at least one child is checked.
This is some kind of code, but it does not work
$('input[type=checkbox]').change(function() {
var id = $(this).attr('id');
var children = $('.parent-' + id);
//Is this a child
if (children.length)
{
//Is it checked
if ($(this).is(':checked'))
{
//Find the parent
var className = $(this).attr('class');
var pId = className.replace("parent-","");
//If the parent is not checked, then check this parent
if (!$(pId).is(':checked'))
$(pId).attr('checked','checked');
}
//Is it NOT checked
else{
//Do other childs are not checked too?
//var className2 = $(this).attr('class');
//$(className2)
}
}
//If this is a parent, then check all childs
esle{
children.attr('checked', $(this).attr('checked'));
}
});
Try this, http://jsfiddle.net/erick/dd6Qr/
// 1. Check all childs if parent is checked
$("#s9").change(function(){
if($(this).is(':checked')) {
var cls = '.parent-' + $(this).attr('id');
$(cls).attr('checked', true);
}
});
$('input[class*="parent"]').change(function(){
var cls = '.' + $(this).attr('class') + ':checked';
var len = $(cls).length;
var parent_id = '#' + $(this).attr('class').split('-')[1];
// 3. Check parent if at least one child is checked
if(len) {
$(parent_id).attr('checked', true);
} else {
// 2. Uncheck parent if all childs are unchecked.
$(parent_id).attr('checked', false);
}
});