0

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.

Related to this post.

1 Answer 1

2

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"));
 });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Tables will be generated from data in MySQL. Would that still work?
Tables or rows? If there's only one table, the code works. Otherwise, you have to use: $(this).closest("table").nextAll("table").
Gotcha. Thanks, @Rob W. You've been a great help.

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.