当用户选中一个父复选框时,我需要检查所有子复选框。例如,如果用户选中id ='s9'
复选框,则必须选中标识为s15
,s16
和s116
的复选框,因为它们具有parentId='s9'
。< / p>
<span class='font-bold'><input id='s1' type='checkbox'/>bla</span><br/>
<span class='left-indent'><input id='s2' parentId='s1' type='checkbox'/>bla11</span><br/>
<span class='left-indent'><input id='s3' parentId='s1' type='checkbox'/>bla12><br/>
<span class='left-indent'><input id='s4' parentId='s1' type='checkbox'/>bla13</span><br/>
<span class='left-indent'><input id='s5' parentId='s1' type='checkbox'/>bla14</span><br/>
<span class='left-indent'><input id='s6' parentId='s1' type='checkbox'/>bla15</span><br/>
<span class='font-bold'><input id='s8' type='checkbox'/>bla2</span><br/>
<span class='font-bold'><input id='s9' type='checkbox'/>bla3</span><br/>
<span class='left-indent'><input id='s15' parentId='s9' type='checkbox'/>bla31</span><br/>
<span class='left-indent'><input id='s16' parentId='s9' type='checkbox'/>bla32</span><br/>
<span class='left-indent'><input id='s116' parentId='s9' type='checkbox'/>bla32</span><br/>
<span class='font-bold'><input id='s10' type='checkbox'/>bla4</span><br/>
<span class='font-bold'><input id='s11' type='checkbox'/>bla5</span><br/>
更新
如果选中某个孩子,也必须检查父母。
如果未选中所有子项,则也必须取消选中父项。
答案 0 :(得分:4)
您不应将parentId
用作自定义属性,因为它会使您的HTML无效。请改用类名:
<input id="s9" type="checkbox" />
<input id="s15" class="parent-s9" type="checkbox" />
<input id="s16" class="parent-s9" type="checkbox" />
示例:强>
$('input[type=checkbox]').change(function() {
// get id of the current clicked element
var id = $(this).attr('id');
// find elements with classname 'parent-<id>' and (un)check them
var children = $('.parent-' + id).attr('checked', $(this).attr('checked'));
});