检查jQuery中的所有复选框

时间:2011-09-23 21:07:49

标签: jquery jquery-selectors

我有一个像这样的表格设置:

<table>
    <thead>
        <th>
            <input type="checkbox" class="check-all" />
        </th>
        <th>
            Title
        </th>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" /></td>
            <td>Name</td>
        </tr>
        <tr>
            <td><input type="checkbox" /></td>
            <td>Name 2</td>
        </tr>
    </tbody>
</table>

我正试着这样做,当选中“check-all”类标题中的复选框时,它会检查下面的所有复选框。

这就是我所拥有的,但它似乎不起作用

        $('.check-all').click(
        function(){
            $(this).parent().parent().parent().find("input[type='checkbox']").attr('checked', $(this).is(':checked'));   
        }
    )

有什么想法吗?谢谢!

3 个答案:

答案 0 :(得分:3)

首先,您应该使用jQuery.closest()来查找最近的表格标记。

 $('.check-all').click(function() {
   $(this).closest('table').find("input:checkbox").attr('checked', this.checked);   
 });

二。如果您使用的是jQuery 1.6或更高版本,则应使用jQuery.prop()

 $('.check-all').click(function() {
   $(this).closest('table').find("input:checkbox").prop('checked', this.checked);   
 });

最后,对于check-all框中的布尔值,您不需要jQuery对象,只需使用HTML DOM this.checked

答案 1 :(得分:0)

我失去了父母的踪迹。 :)试试这个:

$(this).closest("table").find("input[type='checkbox']").attr('checked', $(this).is(':checked'));

编辑:

P.S。 @John Hartsock略微改变了你的语法。我按原样保留了你的语法,但是他的语法更好(或者你可以使用.find(“:checkbox”)。我猜测jquery能够以比获取所有输入更有效的方式找到复选框。然后检查属性“type”以查看它是否为复选框。

答案 2 :(得分:0)

前一阵子{p> I wrote an article about this。如果您将所有相关的复选框设置为相同的类,将会更容易。

<强>更新

Here's a jsFiddle现在我已经有更多时间复制了代码。

HTML

<table>
    <thead>
        <tr>
            <th>
                <input type="checkbox" class="check-all" />
            </th>
            <th>Check All Below</th>
        </tr>
        <tr><th><hr /></th></tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" class="groupOne" /></td>
            <td>Name</td>
        </tr>
        <tr>
            <td><input type="checkbox" class="groupOne" /></td>
            <td>Name 2</td>
        </tr>
    </tbody>
</table>

的JavaScript

var $_checkAll = $('.check-all');
var $_groupOne = $('.groupOne');

$_checkAll.click(function(){
    $_groupOne.prop('checked', $_checkAll.prop('checked'));
});

/* If I uncheck a groupOne checkbox, uncheck the related "check all" */
$_groupOne.click(function(){
    if ( !$(this).prop('checked') ) {
        $_checkAll.prop('checked', false );
    }
});

/* Checking the "check all" checkbox when all groupOne checkboxes 
have been checked is left as homework. */
相关问题