【问题标题】:Check all child checkboxes检查所有子复选框
【发布时间】:2011-03-01 09:55:32
【问题描述】:

当用户选中一个父复选框时,我需要选中所有子复选框。例如,如果用户选中带有id ='s9' 的复选框,则必须选中id 为s15s16s116 的复选框,因为它们具有parentId='s9'

<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/> 

更新

如果检查了某个子项,则也必须检查父项。

如果所有子项都未选中,则父项也必须取消选中。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您不应将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'));
    });
    

    Live example here.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-29
      • 2017-05-26
      • 2013-02-02
      • 2016-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多