Reputation: 383
My original javascript was:
$(document).ready(function(){
$("th :checkbox").change(function() {
$(this).closest("table").find(":checkbox").prop("checked", $(this).is(":checked"));
});
});
which was used on a setting like this:
<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>
I slightly changed how my tables were and it now goes something like:
<table>
<tr>
<th><input type="checkbox" />select all</th>
</tr>
</table>
<table>
<tr>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td><input type="checkbox" /></td>
</tr>
</table>
What do I need to change in my javascript so that when the checkbox in <th>
is checked, all the checkboxes inside the <td>
's in the next table are checked?
Thanks.
Upvotes: 0
Views: 832
Reputation: 348972
Add .next()
to .closest("table")
:
$(document).ready(function(){
$("th :checkbox").change(function() {
$(this).closest("table").next().find(":checkbox").prop("checked", $(this).is(":checked"));
});
});
$(this).closest("table")
selects the table of the element matching th :checkbox
. next()
selects the next element, which is another table, in this case.
This code can break easily. I suggest to set an ID to the other table, and use the following code:
$(document).ready(function(){
$("th :checkbox").change(function() {
$("#id-of-table :checkbox").prop("checked", $(this).is(":checked"));
});
});
Upvotes: 2