简体   繁体   中英

jQuery/Javascript: Check all checkboxes but within a specific table only

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.

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"));
});

使用下面的jQuery

$('input[Type="checkbox"]', $('#tableID')).prop("checked", true);
$('#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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM