开关复选框的选中状态

434

我有以下内容:

$(document).ready(function()
{
    $("#select-all-teammembers").click(function() {
        $("input[name=recipients\\[\\]]").attr('checked', true);
    });                 
});

当点击 id="select-all-teammembers" 时,我希望它可以在选中和未选中之间切换。有什么简洁的代码实现方式吗?

24个回答

789

你可以这样写:

$(document).ready(function() {
    $("#select-all-teammembers").click(function() {
        var checkBoxes = $("input[name=recipients\\[\\]]");
        checkBoxes.prop("checked", !checkBoxes.prop("checked"));
    });                 
});

在jQuery 1.6之前,当我们只有attr()而没有prop()时,我们写的代码是:

checkBoxes.attr("checked", !checkBoxes.attr("checked"));

但是在应用于“boolean”HTML属性时,prop()attr()具有更好的语义,因此在这种情况下通常更受欢迎。


5
如果基于第一个复选框的状态(所以如果用户勾选了第一个复选框,然后使用切换开关,则它们将不同步),这可能会变得复杂。稍微调整一下,使其以切换开关而不是列表中的第一个复选框为基础来确定状态:$("input[name=recipients\[\]]").prop("checked", $(this).prop("checked"))。 - CookiesForDevo
6
使用 'prop' 将使此功能也适用于 Zepto。否则,它会勾选复选框,但不会取消勾选。 - SimplGy
1
使用 "prop" 替代 "attr" 就解决了问题: 使用 "attr" 时,切换会持续一段时间然后停止,而使用 "prop" 时,它的切换表现如预期。为这次更新点个赞。 - Niki Romagnoli
13
@2astalavista提到的$('input[type=checkbox]').trigger('click');更加简洁,同时也会触发“change”事件。 - here
1
你能否编辑你的回答以支持@CookiesForDevo的答案? - acquayefrank
显示剩余11条评论

237
//this toggles the checkbox, and fires its event if it has    

$('input[type=checkbox]').trigger('click'); 
//or
$('input[type=checkbox]').click(); 

在Chrome 29中有效,但在FF 17.0.7中无效,可以有人确认吗? - Gerrit-K
我一直在改变属性的路上走了很久。对我来说,这是一种更好、更灵活的方法,用于检查和取消选中复选框元素。 - Isioma Nnodum
2
不需要的事件被触发。 - Jehong Ahn
1
对于复选框,通常更建议触发“change”事件,因为它们可以通过单击标签进行更改。 - Peter Mghendi
我也喜欢这个,因为它很简单,但正如@PeterLenjo所说,你必须调整一些东西来适应在标签上点击的情况。我只是完全防止了标签切换复选框的功能。 - Nathan

74

我知道这篇文章有点老了,但问题有点含糊不清,因为toggle可能意味着每个复选框都应该切换其状态,无论它是什么。如果有3个选中和2个未选中,那么切换会使前3个未选中,后2个选中。

对于这一点,这里的解决方案都不起作用,因为它们让所有复选框的状态都相同,而不是切换每个复选框的状态。在多个复选框上执行$(':checkbox').prop('checked')将返回所有.checked二进制属性之间的逻辑AND运算,即如果其中一个未选中,则返回值为false

如果您想要实际切换每个复选框的状态而不是使它们全部相等,您需要使用.each(),例如:

   $(':checkbox').each(function () { this.checked = !this.checked; });

请注意,在处理函数内不需要使用$(this),因为.checked属性在所有浏览器中都存在。


6
是的,这是切换所有复选框状态的正确答案! - Sydwell
2
当你有很多复选框时,比使用jQuery触发点击事件快几个数量级。 - Jeremy Cook

16

这里是另外一种你想要的方式。

$(document).ready(function(){   
    $('#checkp').toggle(
        function () { 
            $('.check').attr('Checked','Checked'); 
        },
        function () { 
            $('.check').removeAttr('Checked'); 
        }
    );
});

2
@kst - 这是一种更好的方法 $('input[name=recipients\[\]]').toggle(this.checked); 忘记类。 - Davis

13

我能想到的最好的方法。

$('#selectAll').change(function () {
    $('.reportCheckbox').prop('checked', this.checked);
});
$checkBoxes = $(".checkBoxes");
$("#checkAll").change(function (e) {
    $checkBoxes.prop("checked", this.checked);
});   
或者
<input onchange="toggleAll(this)">
function toggleAll(sender) {
    $(".checkBoxes").prop("checked", sender.checked);
}

13

我认为更简单的方法是触发点击事件:

$("#select-all-teammembers").click(function() {
    $("input[name=recipients\\[\\]]").trigger('click');
});                 

非常有效,因为它还会启动目标复选框的“onclick”函数。 - JonV

10

请使用这个插件:

$.fn.toggleCheck  =function() {
       if(this.tagName === 'INPUT') {
           $(this).prop('checked', !($(this).is(':checked')));
       }

   }

然后

$('#myCheckBox').toggleCheck();

对我来说,直到我像这样更改if语句,你的解决方案才起作用: if(this[0].tagName === 'INPUT') - snecserc

9
自从jQuery 1.6版本以后,你可以使用.prop(function)来切换每个找到的元素的选中状态。该方法链接为:.prop(function)
$("input[name=recipients\\[\\]]").prop('checked', function(_, checked) {
    return !checked;
});

非常好的回答。你是否了解更多有关将下划线作为第一个参数传递的信息?我可以在哪里学到更多相关知识呢? - user1477388
1
编辑:显然,这是一种传递空值的方法。https://dev59.com/gWgu5IYBdhLWcg3wU1mN - user1477388
这个真的很棒 - 我已经寻找一个 proptoggle 一段时间了,这个运行得非常干净。 - Stender

2
<table class="table table-datatable table-bordered table-condensed table-striped table-hover table-responsive">
<thead>
    <tr>
        <th class="col-xs-1"><a class="select_all btn btn-xs btn-info"> Select All </a></th>
        <th class="col-xs-2">#ID</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td><input type="checkbox" name="order333"/></td>
        <td>{{ order.id }}</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="order334"/></td>
        <td>{{ order.id }}</td>
    </tr>
</tbody>                  
</table>

尝试:

$(".table-datatable .select_all").on('click', function () {
    $("input[name^='order']").prop('checked', function (i, val) {
        return !val;
    });
});

2
这是一种使用jQuery的方法,在不需要通过html5和标签选择复选框的情况下进行切换:
 <div class="checkbox-list margin-auto">
    <label class="">Compare to Last Year</label><br>
    <label class="normal" for="01">
       <input id="01" type="checkbox" name="VIEW" value="01"> Retail units
    </label>
    <label class="normal" for="02">
          <input id="02" type="checkbox" name="VIEW" value="02">  Retail Dollars
    </label>
    <label class="normal" for="03">
          <input id="03" type="checkbox" name="VIEW" value="03">  GP Dollars
    </label>
    <label class="normal" for="04">
          <input id="04" type="checkbox" name="VIEW" value="04">  GP Percent
    </label>
</div>

  $("input[name='VIEW']:checkbox").change(function() {
    if($(this).is(':checked')) {  
         $("input[name='VIEW']:checkbox").prop("checked", false);
     $("input[name='VIEW']:checkbox").parent('.normal').removeClass("checked");
         $(this).prop("checked", true);
         $(this).parent('.normal').addClass('checked');
    }
    else{
         $("input[name='VIEW']").prop("checked", false);
         $("input[name='VIEW']").parent('.normal').removeClass('checked');
    }    
});

http://www.bootply.com/A4h6kAPshx


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接