1

Just needing a little help here. To start off, here's what my HTML looks like:

<div>
<table id="table" width="100%">
<tr>
    <th><input type="checkbox" />Select All</th>
    <th>A</th>
    <th>B</th>
    <th>C</th>
    <th>D</th>
</tr>
<tr>
    <td><input type="checkbox" /></td>
    <td>A</td>
    <td>B</td>
    <td>C</td>
    <td>D</td>
</tr>
</table>
</div>

There's 5 more tables like this in a single page and what I'm meaning to do is that when the <th> checkbox is ticked on a certain table, only the <td> checkboxes within that certain table will be checked. Any help on how this will be done would be greatly appreciated.

3 Answers 3

4

You can get bind a change event handler to all checkboxes that are descendants of a th element, and then check all checkboxes that are descendants of the closest table:

$("th :checkbox").change(function() {
    $(this).closest("table").find(":checkbox").prop("checked", true);
});

Here's a working example with 2 tables. If you want the checkbox in the th to uncheck all the other checkboxes too, then you can do this, using the second argument of prop (thanks @SalmanA):

$("th :checkbox").change(function() {
    $(this).closest("table").find(":checkbox").prop("checked", $(this).is(":checked"));
});
Sign up to request clarification or add additional context in comments.

7 Comments

You can eliminate the if-else by ... .prop("checked", $(this).is(":checked"));
@SalmanA - Good call. I've edited the answer to use that instead. I always forget that one :)
@James Does it matter if I have my tables wrapped in a div?
@MikeSanchez - No, that won't make any difference. The th :checkbox selector only cares about checkboxes in th elements, and the closest method will find the closest table and go no futher.
@James Thanks for the help, buddy. I was using an outdated jQuery file which made it not work. It's all working now. Again, thanks.
|
1

Use the below jquery

$('input[Type="checkbox"]', $('#tableID')).prop("checked", true);

Comments

1
$('#table input:checkbox').prop('checked', true);

To bind this event for each checkbox in the th tags (as in James Allardice's answer)

$('th :checkbox').change(function() {
    $(':checkbox', $(this).closest('table')).prop('checked', true);
});

1 Comment

I think the OP wants it to apply separately to all of his 5 tables. This will only work for #table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.