本文介绍了父母和子女复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<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 some checkboxes on a page. I have need:
- 如果选中父母,请检查所有孩子。
- 如果所有孩子都取消选中父母未经检查。
- 如果至少检查了一个孩子,请检查父母。
这是一些一些代码,但它不起作用
This is some some code, but it's doesn't 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'));
}
});
推荐答案
这里我为你编写代码:
Here I wrote code for you: http://jsfiddle.net/PUWZX/4/
这篇关于父母和子女复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!