Search code examples
jquerycheckboxchecked

Need help with jquery checkboxes set


I have a DOM structure sometihng like this (I don't want to show other td's because of overcrowding):

<table>
<tr><td><input type="checkbox" name="checkbox1" class="rowSelectCheckbox"></td></input></tr>
<tr><td><input type="checkbox" name="checkbox2" class="rowSelectCheckbox"></td></input></tr>
<tr><td><input type="checkbox" name="checkbox3" class="rowSelectCheckbox"></td></input></tr>
<tr><td><input type="checkbox" name="checkbox4" class="rowSelectCheckbox"></td></input></tr>

</table>

<input type="checkbox" name="checkbox_select" id="lastCheckbox"></input>

What I'm trying to do is set the last checkbox with the id of lastCheckbox to checked if any of the other checkboxes are checked (any of those with id of checkbox1, checkbox 2 etc), otherwise if all the other checkboxes are unchecked, set this last checkbox to unchecked too.


Solution

  • Try this:

    $('.rowSelectCheckbox').change( function() {
        $('.rowSelectCheckbox').each( function() {
            if ($(this).prop('checked')) {
                $('#lastCheckbox').prop('checked', true);
                return false;
            }
    
            $('#lastCheckbox').prop('checked', false);
        } );
    } );
    

    Fiddle: http://jsfiddle.net/B78vP/