【问题标题】:Checking at least one checkbox within groups of checkboxes检查复选框组中的至少一个复选框
【发布时间】:2014-03-27 17:22:07
【问题描述】:

我在标签中有一组复选框,就像这样

<div class="constraints">
<label>
    <label>
        <input type="checkbox" ...>
    </label>
    .
    .
    .
    <label>
        <input type="checkbox" ...>
    </label>
</label>
.
.
.
<label>
    <label>
        <input type="checkbox" ...>
    </label>
    .
    .
    .
    <label>
        <input type="checkbox" ...>
    </label>
</label>
</div>

在每组标签 (.constraints &gt; label) 中,必须至少选中一个复选框。为了确保这一点,我编写了这个 jQuery 代码,如果所有这些都未选中,则应该简单地勾选组中的第一个框。

$('form .constraints input').on('change', function() {
    var checks = $(this).closest('.constraints > label').find('input') ;

    var atleastone = false ;

    checks.each(function() {
        if ($(this).is(':checked')) {
            atleastone = true ;
        }
    }) ;

    if (!atleastone) {
        checks.first().attr('checked', true) ;
    }
}) ;

只工作一次。我第一次选中或取消选中 任何 个框时,脚本可以工作,但任何后续调用都不会产生任何结果。

出了什么问题?

【问题讨论】:

    标签: javascript jquery forms checkbox


    【解决方案1】:

    你需要改变你拥有的每一个地方

    .attr('checked')
    .attr('checked', true)
    

    .prop('checked')
    .prop('checked', true)
    

    要了解原因,您可以查看.prop() vs .attr()

    你可以通过这样做大大缩短你的代码

    $('form .constraints input').on('change', function() {
      var checks = $(this).closest('.constraints > label').find('input');
      var checked = checks.filter(':checked').length == 0;
      if (checked) checks.first().prop('checked', checked);
    });
    

    【讨论】:

    • 我知道它一定是一些我想念的简单而愚蠢的东西。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多