<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>
頁面上有一些複選框。我需要:父母和子女複選框
- 檢查所有孩子是否選中父母。
- 如果所有孩子都未選中,請取消選中父母。
- 如果至少有一個孩子被選中,則檢查父代。
這是一些一些代碼,但它不工作
$('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'));
}
});
完美!謝謝。 – Alexandre 2011-03-01 14:13:07
很高興幫助:) – CoolEsh 2011-03-01 14:19:07
也許簡化這樣的功能片段:'parentClicked:function(){var parentCheck = this.checked; $('#customerServices input:checkbox [class =「parent-'+ $(this).attr('id')+'」]')。each(function(){this.checked = parentCheck;}); },' – 2011-03-01 17:58:03