jQuery 打开/关闭复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4177159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:47:34  来源:igfitidea点击:

Toggle Checkboxes on/off

jquerycheckboxjquery-selectorstoggle

提问by AnApprentice

I have the following:

我有以下几点:

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

I'd like the id="select-all-teammembers"when clicked to toggle between checked and unchecked. Ideas? that aren't dozens of lines of code?

我想要id="select-all-teammembers"点击时在选中和未选中之间切换。想法?那不是几十行代码吗?

回答by Frédéric Hamidi

You can write:

你可以写:

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

Before jQuery 1.6, when we only had attr()and not prop(), we used to write:

在 jQuery 1.6 之前,当我们只有attr()而没有prop() 时,我们曾经这样写:

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

But prop()has better semantics than attr()when applied to "boolean" HTML attributes, so it is usually preferred in this situation.

但是prop()attr()应用于“布尔值”HTML 属性时具有更好的语义,因此在这种情况下通常首选。

回答by AnApprentice

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

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

回答by Normadize

I know this is old but the question was a bit ambiguous in that togglemay mean each checkbox should toggle its state, whatever that is. If you have 3 checked and 2 unchecked, then toggling would make the first 3 unchecked and the last 2 checked.

我知道这是旧的,但这个问题有点模棱两可,因为切换可能意味着每个复选框都应该切换它的状态,不管它是什么。如果您有 3 个选中和 2 个未选中,则切换将使前 3 个未选中,最后 2 个选中。

For that, none of the solutions here work as they make all the checkboxes have the same state, rather than toggle each checkbox's state. Doing $(':checkbox').prop('checked')on many checkboxes returns the logical AND between all .checkedbinary properties, i.e. if one of them is unchecked, the returned value is false.

为此,这里的解决方案都不起作用,因为它们使所有复选框具有相同的状态,而不是切换每个复选框的状态。这样做$(':checkbox').prop('checked')在很多复选框返回逻辑和所有之间的.checked二元性,即如果其中一人被选中时,返回的值是false

You need to use .each()if you want to actually toggle each checkbox state rather than make them all equal, e.g.

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

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

Note that you don't need $(this)inside the handler as the .checkedproperty exists in all browsers.

请注意,您不需要$(this)在处理程序内部,因为该.checked属性存在于所有浏览器中。

回答by kst

Here is another way that you want.

这是您想要的另一种方式。

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

回答by matt burns

I think it's simpler to just trigger a click:

我认为触发点击更简单:

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

回答by Dblock247

The best way I can think of.

我能想到的最好的方法。

$('#selectAll').change(function () {
    $('.reportCheckbox').prop('checked', this.checked);
});

or

或者

$checkBoxes = $(".checkBoxes");
$("#checkAll").change(function (e) {
    $checkBoxes.prop("checked", this.checked);
});   

or

或者

<input onchange="toggleAll(this)">
function toggleAll(sender) {
    $(".checkBoxes").prop("checked", sender.checked);
}

回答by Abdennour TOUMI

Use this plugin :

使用这个插件:

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

   }

Then

然后

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

回答by Ja?ck

Since jQuery 1.6 you can use .prop(function)to toggle the checked state of each found element:

从 jQuery 1.6 开始,您可以使用.prop(function)来切换每个找到的元素的选中状态:

$("input[name=recipients\[\]]").prop('checked', function(_, checked) {
    return !checked;
});

回答by Anatoly

Check-all checkbox should be updated itselfunder certain conditions. Try to click on '#select-all-teammembers'then untick few items and click select-all again. You can see inconsistency. To prevent it use the following trick:

入住所有复选框应该更新自身在一定条件下。尝试单击“#select-all-teammembers”,然后取消勾选几个项目,然后再次单击全选。你可以看到不一致。为了防止它使用以下技巧:

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

BTW all checkboxes DOM-object should be cached as described above.

顺便说一句,所有复选框 DOM 对象都应如上所述进行缓存。

回答by user1428592

Assuming that it's an image that has to toggle the checkbox, this works for me

假设它是一个必须切换复选框的图像,这对我有用

<img src="something.gif" onclick="$('#checkboxid').prop('checked', !($('#checkboxid').is(':checked')));">
<input type="checkbox" id="checkboxid">