【问题标题】:how to check all the checkbox with two different class如何检查具有两个不同类别的所有复选框
【发布时间】:2014-01-15 17:36:57
【问题描述】:

我正在尝试选中/取消选中所有复选框,这样如果选中/取消选中其中一个复选框,则所有复选框都将被选中/取消选中。

这是我的代码:

HTML:

<th><input type="checkbox" name="pay" id="chkAll"  class="chkAll"/>With Pay</th>
<th><input type="checkbox" name="pay" id="chkAll2" class="chkAll2"/>Without Pay</th>    


<td><input type="checkbox" name="pay" value="With Pay" class="chk" id="chk"/></td>
<td><input type="checkbox" name="pay" value="Without Pay" class="chk2"  id="chk2"/></td>

JS:

 $('.chkAll').change(function () {
     var id = $(this).attr("id").replace("check_", "");
     if ($(this).is(':checked')) {
         $(".chk").prop('checked', true);
         $(".chk2").prop('checked', false);
         $('.chkAll2').prop('checked', false);
     } else {
         $(".chk").prop('checked', false);
     }
 });

 $('.chkAll2').change(function () {
     var id = $(this).attr("id").replace("check_", "");
     if ($(this).is(':checked')) {
         $(".chk2").prop('checked', true);
         $(".chk").prop('checked', false);
         $('.chkAll').prop('checked', false);
     } else {
         $(".chk2").prop('checked', false);
     }
 });

 $('.chk').not('[id^=chkAll]').change(function () {
     if ($(this).is(':checked')) {
         $('.chkAll').prop('checked', true);
     } else {
         $('.chkAll').prop('checked', false);
     }
 });

【问题讨论】:

  • 对多个 html 元素使用相同的 id 并不好。您应该为此使用 class

标签: javascript jquery checkbox


【解决方案1】:

试试

jQuery(function () {

    function checkAll($all, $els) {
        $all.change(function () {
            $els.prop('checked', this.checked);
        });
        $els.change(function () {
            $all.prop('checked', $els.not(':checked').length == 0);
        });
    }

    checkAll($('#chkAll'), $('.chk'))
    checkAll($('#chkAll2'), $('.chk2'))
})

演示:Fiddle

【讨论】:

  • 感谢它有效:) 我有最后一个问题。如果在我选中其中一个有支付的情况下检查所有无薪,则无薪复选框将被取消选中,并且以下 的无薪
  • 在检查 td("withpay") 时,所有无偿的复选框都将被取消选中,然后另一个并行 td 将被取消选中....对不起我的语法
【解决方案2】:

这里是简单的 jQuery 代码

$(document).ready(function(){
    $('.chk-all').on('change', function(){
        $('.' + $(this).data('child')).prop('checked',this.checked);
    });
});

用于跟随 HTML

<table>
    <thead>
        <tr>
            <th><input type="checkbox" name="pay"   class="chk-all" data-child='child-1'/>With Pay</th>
            <th><input type="checkbox" name="pay"  class="chk-all" data-child='child-2'/>Without Pay</th>
        </tr>
    </thead>    
    <tbody>
        <tr>
            <td><input type="checkbox" name="pay" value="With Pay" class="child-1" /></td>
            <td><input type="checkbox" name="pay" value="Without Pay" class="child-2"  /></td>
        </tr>
        <tr>
            <td><input type="checkbox" name="pay" value="With Pay" class="child-1" /></td>
            <td><input type="checkbox" name="pay" value="Without Pay" class="child-2" /></td>
        </tr>
    </tbody>
</table>

检查这个Fiddle

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签