【问题标题】:How can I check multiple check boxes in jQuery? [duplicate]如何在 jQuery 中选中多个复选框? [复制]
【发布时间】:2013-08-18 10:48:10
【问题描述】:

我有一个表格,每行开头都有一个复选框。每个 Checkbox 的 ID 为#tablecheckbox。表头行有一个复选图标,应该选中表中的所有框。我怎么能用 jQuery 做到这一点?

【问题讨论】:

  • 你已经尝试了什么?
  • ^^ 和 ID 应该是唯一的。
  • 让你的 ids 成为一个类,然后点击这个链接:stackoverflow.com/questions/426258/…
  • 而不是使用 id 尝试使用名称属性,它可以帮助检查所有复选框。
  • 能否请您显示您的表格的代码(至少是标题和几行正文)?

标签: javascript jquery html checkbox


【解决方案1】:

这里的 head_checkbox 是顶部标题的 id,而 person 类是所有行的复选框

 $('#head_checkbox').on('change', function () {
            if ($(this).is(':checked')) {
                $('.person').attr('checked', true);
            } else {
                $('.person').attr('checked', false);
            }
        });

        $('.person').click(function () {
            var total_length = $('.person').length;
            var total_checked_length = $('.person:checked').length;

            if (total_length == total_checked_length) {
                $('#head_checkbox').attr('checked', true);
            } else {
                $('#head_checkbox').attr('checked', false);
            }
        });

【讨论】:

  • live 已被弃用,因为应该使用 1.7 on() 来代替
  • 我曾经设置document.getElementById("head_checkbox").checked属性。你的方法似乎更干净。谢谢。
【解决方案2】:
       $('#head_checkbox').click(function () {
            if ($(this).is(':checked')) {
                $('.person').attr('checked', true);
            } else {
                $('.person').attr('checked', false);
            }
        });


        $('.person').click(function () {
            if ($('.person').length == $('.person:checked').length) {
                $('#head_checkbox').attr('checked', true);
            } else {
                $('#head_checkbox').attr('checked', false);
            }
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 2018-09-17
    相关资源
    最近更新 更多