我有以下几点:

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

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


当前回答

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

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

其他回答

最基本的例子是: //获取DOM元素 var checkbox = document.querySelector('input'), button = document.querySelector('button'); //在按钮上绑定“cilck”事件 按钮。addEventListener(“点击”,toggleCheckbox); //当单击按钮时,切换复选框 函数toggleCheckbox () { 复选框。checkbox.checked = ! }; < input type = "复选框”> < / > <按钮切换复选框按钮>

我认为触发点击更简单:

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

我知道这是老问题,但这个问题有点模棱两可,因为toggle可能意味着每个复选框都应该切换其状态,无论它是什么。如果有3个选中,2个未选中,那么切换将使前3个未选中,最后2个选中。

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

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

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

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

你可以这样写:

$(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"));

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

您还可以通过执行以下操作来切换复选框。目前使用引导切换复选框。

<link href='https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css' rel='stylesheet'>
<script src='https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js'></script>

<input type='checkbox' id='toggleScheduler' name='toggleScheduler' data-toggle='toggle'  data-on='Enabled'  data-off='Disabled'

$("#toggleScheduler").bootstrapToggle('on'); // enable toggle checkbox
$("#toggleScheduler").bootstrapToggle('off'); // disable toggle checkbox