使用jQuery切换检查/取消选中多个复选框列表

时间:2012-02-22 00:00:58

标签: jquery checkbox toggle

我在检查和取消选中(选择并取消选择全部)复选框列表时遇到两个问题:

  1. 父复选框不会选中/取消选中。
  2. 我只需选择孩子。
  3. 示例:

    http://jsfiddle.net/TheFiddler/v6wmV/

    $(document).ready(function(){
        $('.all').toggle(
            function() {
                $('.check').find('input[type=checkbox]').attr('checked', true);
            },
            function() {
                $('.check').find('input[type=checkbox]').attr('checked', false);
            });
    });
    

    现在,我在一个类上有事件,并且由于这两个复选框列表共享了这个类,所以它们都会切换。

2 个答案:

答案 0 :(得分:6)

<强> Demo

$(document).ready(function(){ 
    $('.all').click(function() {
        var $checkboxes = $(this).parent().find('input[type=checkbox]');
        $checkboxes.prop('checked', $(this).is(':checked'));
    });     
});  

HTML

<div class="check">
      <input type="checkbox" class="all" /> Check/Uncheck all<br />
      <input type="checkbox" /> 1<br />
      <input type="checkbox" /> 2<br />
      <input type="checkbox" /> 3<br />
      <input type="checkbox" /> 4<br />
      <input type="checkbox" /> 5<br />
      <input type="checkbox" /> 6<br />
      <input type="checkbox" /> 7
</div>
...

答案 1 :(得分:1)

上面的好帖子。使用每个功能的另一种方式,虽然它不仅仅使用孩子。

&#13;
&#13;
jQuery('.check-all').click(function() {
      jQuery('.checked-rec').each(function() {
        $(this).attr('checked', $('.check-all').is(':checked'));
      })
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<thead>
  <tr>
    <th>
      <input type="checkbox" class="check-all">
    </th>
  </tr>
</thead>

<tbody>

  <tr class="odd gradeX">
    <td>
      <input type="checkbox" class="checked-rec">
    </td>
  </tr>

  <tr class="odd gradeX">
    <td>
      <input type="checkbox" class="checked-rec">
    </td>
  </tr>

  <tr class="odd gradeX">
    <td>
      <input type="checkbox" class="checked-rec">
    </td>
  </tr>

  <tr class="odd gradeX">
    <td>
      <input type="checkbox" class="checked-rec">
    </td>
  </tr>

</tbody>
&#13;
&#13;
&#13;