views:

291

answers:

2

Hello everyone!
I need help with jQuery selectors. Say I have a markup as shown below:

<form>
    <table>
        <tr>
            <td><input type="checkbox" id="select_all"/></td>
        </tr>
        <tr>
            <td><input type="checkbox" name="select[]"/></td>
        </tr>
        <tr>
            <td><input type="checkbox" name="select[]"/></td>
        </tr>
        <tr>
            <td><input type="checkbox" name="select[]"/></td>
        </tr>
    </table>
</form>

How to get all checkboxes except #select_all when user clicks on it?
Any help will be appreciated.

+2  A: 
$("form input[type='checkbox']").attr ( "checked" , true );

or you can use the

:checkbox Selector

$("form input:checkbox").attr ( "checked" , true );

I have rewritten your HTML and provided a click handler for the main checkbox

$(function(){
  $("#select_all").click ( function(){
   $("#frm1 input[type='checkbox'].child").attr ( "checked" , $(this).attr("checked" ) );
  });
});

<form id="frm1">
    <table>
        <tr>
            <td>
                <input type="checkbox" id="select_all" />
            </td>
        </tr>
        <tr>
            <td>
                <input type="checkbox" name="select[]" class="child" />
            </td>
        </tr>
        <tr>
            <td>
                <input type="checkbox" name="select[]" class="child" />
            </td>
        </tr>
        <tr>
            <td>
                <input type="checkbox" name="select[]" class="child" />
            </td>
        </tr>
    </table>
    </form>
rahul
Just beware to don't check every checkbox on the page... :)
TiuTalk
Actually, the correct syntax is `.attr("checked", "checked")`.
Tatu Ulmanen
+1 Thanks rahul, but I needed to find all checkboxes when user clicks on #select_all checkbox.
Darmen
+3  A: 

A more complete example that should work in your case:

$('#select_all').change(function() {
    var checkboxes = $(this).closest('form').find(':checkbox');
    if($(this).is(':checked')) {
        checkboxes.attr('checked', 'checked');
    } else {
        checkboxes.removeAttr('checked');
    }
});

When the #select_all checkbox is clicked, the status of the checkbox is checked and all the checkboxes in the current form are set to the same status.

Note that you don't need to exclude the #select_all checkbox from the selection as that will have the same status as all the others. If you for some reason do need to exclude the #select_all, you can use this:

var checkboxes = $(this).closest('form').find(':checkbox').not($(this));
Tatu Ulmanen
Thanks, Tatu! That's what I need
Darmen