2011-09-23 35 views
1

我有一个表的设置是这样的:检查所有的复选框中的jQuery

<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').click(
     function(){ 
      $(this).parent().parent().parent().find("input[type='checkbox']").attr('checked', $(this).is(':checked')); 
     } 
    ) 

任何想法?谢谢!

回答

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

最后,从一个布尔值检查所有的框,你不需要,你可以简单地使用HTML DOM this.checked

0

我jQuery对象失去父母的踪迹。 :)试试这个:

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

编辑:

附: @John Hartsock稍微改变了你的语法。我留下了你的语法,但他的语法更好(或者你可以使用.find(“:checkbox”)。我猜jQuery能找到复选框的方法比获取所有输入和然后检查属性“类型”,看它是否是一个复选框。

0

I wrote an article about this而回,这将是更容易,如果你给所有相关的复选框同一类。

UPDATE

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. */