How to select all checkboxes with jQuery?(如何使用 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 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 选择所有复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!