【问题标题】:How to checked checkbox main when sub checkbox not checked?未选中子复选框时如何选中主复选框?
【发布时间】:2014-09-14 16:37:52
【问题描述】:

未选中子复选框时如何检查主复选框?

当复选框 id="checkItem1"id="checkItem2"id="checkItem3" 未选中时,

我想自动选中复选框id="checkAll" 我该怎么做?

http://jsfiddle.net/peap/sydzL8Lc/11/

<input type="checkbox" id="checkAll" checked > Check All
<hr />
<input type="checkbox" id="checkItem1"> Item 1
<input type="checkbox" id="checkItem2"> Item 2 
<input type="checkbox" id="checkItem3"> Item3 

【问题讨论】:

  • 一只土拨鼠能吃多少木头...

标签: javascript jquery checkbox


【解决方案1】:

你可以这样做

$('input[id^="checkItem"]').change(function(){
    if($('input[id^="checkItem"]:checked').length===0)
        $('#checkAll').prop('checked',true);
})

DEMO

【讨论】:

  • 我可以拆分 id 复选框吗?
  • @การกรกรกรกกกนรกี 对不起,我没听明白,你说的拆分 ID 是什么意思?
  • 在代码中使用例如 checkItem1 、 checkItem2 、 checkItem3 。
【解决方案2】:

我对您需要的全部功能进行了JSFiddle,包括当用户单击 checkAll 时,如果 checkAll 被选中,所有框都变为选中,否则不选中。此外,它们每个都有一个 on change 监听器,用于监听用户是否检查了所有这些监听器,并将 checkAll 更改为已选中并向后更改。

HTML:

<input type="checkbox" id="checkAll"> Check All
    <hr />
    <div class='js-checkboxes'>
    <input type="checkbox" id="checkItem1"> Item 1
    <input type="checkbox" id="checkItem2"> Item 2 
    <input type="checkbox" id="checkItem3"> Item3
    </div>

Javascript:

$('.js-checkboxes > input').on('change', function() {
    var isAllChecked = true;

    $('.js-checkboxes > input').each(function() {
        if (!this.checked) {
            isAllChecked = false;
        }
    });

    if (isAllChecked) {
        $('#checkAll')[0].checked = true;
    } else {
        $('#checkAll')[0].checked = false;
    }
});

$('#checkAll').on('change', function() {
    if (this.checked) {
        $('.js-checkboxes > input').each(function() {
            this.checked = true;
        });
    } else {
        $('.js-checkboxes > input').each(function() {
            this.checked = false;
        });
    }
});

【讨论】:

    【解决方案3】:
    $("input[id^='checkItem']").change(function(){
       if(!$("#checkItem1").is(":checked") && !$("#checkItem2").is(":checked") && !$("#checkItem3").is(":checked"))
       {
          $("#checkAll").prop("checked",true)
       }
    }
    

    编辑:- DEMO

    【讨论】:

    • 如果用户取消选中checkAll 复选框怎么办?您将其设置为选中
    • @charlietfl..我只是按照问题回答了我在回答过程中无法给出自己的意见。
    • 这不是意见,事件处理程序不应该绑定到页面上的所有复选框,让用户无法取消选中某些内容
    • @charlietfl...okk 解决了这个问题,但这不是大问题,我认为这不是投票失败的原因..
    • @balexandre...plzz 看到更新的答案我认为这就是你所指出的......
    猜你喜欢
    • 2021-11-23
    • 2013-09-29
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多