使用jQuery选择所有复选框 [英] Select all checkboxes with jQuery

查看:167
本文介绍了使用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?
Any help will be appreciated.

推荐答案

一个更完整的例子工作在你的情况下:

A more complete example that should work in your case:

$('#select_all').change(function() {
    var checkboxes = $(this).closest('form').find(':checkbox');
    if($(this).is(':checked')) {
        checkboxes.prop('checked', true);
    } else {
        checkboxes.prop('checked', false);
    }
});

当单击 #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:

var checkboxes = $(this).closest('form').find(':checkbox').not($(this));

这篇关于使用jQuery选择所有复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆