如何使用jQuery选择所有复选框? [英] How to select all checkboxes with jQuery?
问题描述
我需要有关jQuery选择器的帮助。假设我有一个标记,如下所示:
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>
如何获取用户单击时除 #select_all
以外的所有复选框?
How to get all checkboxes except #select_all
when user clicks on it?
推荐答案
A适用于您的情况的更完整示例:
A more complete example that should work in your case:
$('#select_all').change(function() {
var checkboxes = $(this).closest('form').find(':checkbox');
checkboxes.prop('checked', $(this).is(':checked'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
当 #select_all
复选框被选中,该复选框的状态被选中,并且当前表单中的所有复选框都被设置为相同的状态。
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.
请注意,您无需从选择中排除 #select_all
复选框,因为该复选框的状态将与其他所有复选框相同。如果出于某些原因确实需要排除 #select_all
,则可以使用以下命令:
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:
$('#select_all').change(function() {
var checkboxes = $(this).closest('form').find(':checkbox').not($(this));
checkboxes.prop('checked', $(this).is(':checked'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
这篇关于如何使用jQuery选择所有复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!