简体   繁体   English

jQuery选中所有不起作用的复选框

[英]jQuery check all not working on checkboxes

I'm writing some code that will allow the following: 我正在编写一些允许以下操作的代码:

1.) If a user checks a checkbox it will change the parent <tr> to have a class of selected (this can also be unchecked and remove the class) 1.)如果用户选中一个复选框,它将更改父级<tr>以选择一个类(也可以取消选中并删除该类)

2.) Any checkboxes that are already checked will have the class added on document load 2.)任何已选中的复选框都会在文档加载时添加该类

3.) If a user checks the #checkall input then all inputs will become checked and add the class of selected (if checked again then it will unselect all and remove the class) 3.)如果用户检查#checkall输入,则所有输入都将变为选中状态并添加所选类别(如果再次选中,则它将取消选中所有类别并删除该类别)

This is the code I have so far: 这是我到目前为止的代码:

$("table input[name=choose]:checked").each(function()
    {
        $(this).closest("tr").addClass("selected");
    });

    $("table input[name=choose]").live("change", function()
    {
        $(this).closest("tr").toggleClass("selected");
    });

    if ($('#checkall:checked') ==  true)
    {
        $('#checkall').live("click", function()
        {
            $('table input[name=choose]').attr('checked', false);
            $('table input[name=choose]').closest("tr").toggleClass("selected");              
        });
    }
    else
    {
        $('#checkall').live("click", function()
        {
            $('table input[name=choose]').attr('checked', true);
            $('table input[name=choose]').closest("tr").toggleClass("selected");
        });
    }

The first two work fine but number 3 doesn't uncheck the checkboxes... Any ideas why? 前两个可以正常工作,但是数字3不会取消选中复选框...任何想法为何? But the class part works fine?? 但是上课的部分工作正常吗?

Thanks 谢谢

I guess it runs always into the else block (have you debugged this)? 我猜它总是会碰到else块(您已经调试了吗)?

Try writing this for checking if the checkbox is checked: 尝试编写以下代码检查复选框是否被选中:

if ($('#checkall').attr('checked'))

Because if ($('#checkall:checked') == true) is always false.. 因为if ($('#checkall:checked') == true)始终为false。

either use 要么使用

if ($('#checkall').is(':checked'))

or 要么

if ( $('#checkall:checked').length )

Update after comment 评论后更新

Replace the entire third part ( all the if/else ) with 将整个第三部分( 所有if / else )替换为

$('#checkall').live("change", function()
        {
            $('table input[name=choose]')
                 .attr('checked', this.checked)
                 .closest("tr")
                 .toggleClass("selected", this.checked);              
        });

demo at http://jsfiddle.net/gaby/KqwsZ/1/ 演示在http://jsfiddle.net/gaby/KqwsZ/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM