简体   繁体   中英

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)

2.) Any checkboxes that are already checked 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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