开发者

jQuery check all not working on checkboxes

开发者 https://www.devze.com 2023-04-10 08:41 出处:网络
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

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)

2.) Any checkboxes that are already che开发者_StackOverflowcked will have the class added on document load

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)

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? But the class part works fine??

Thanks


I guess it runs always into the else block (have you debugged this)?

Try writing this for checking if the checkbox is checked:

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


Because if ($('#checkall:checked') == true) is always 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

$('#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/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号