选中所有复选框时,选择一个复选框


Select one Checkbox When All chekboxes are selected

我正在寻找这样一种逻辑,在该逻辑中,我使用php获取while循环中的一些数据列表,如下所示。

  if (mysql_num_rows($results) != 0) {
      // displaying records.
      while ($row = mysql_fetch_array($results)) {
          echo '<div id="checkboxlist">';
          echo '<tr>';
          echo '<td><input name="checkbox[]" type="checkbox" class="checkbox1" value="'.$row['Id'].'" id="Checkbox1"></td>';
          echo '<td>'.$row['first_name'].'</td>';
          echo '<td>'.$row['last_name'].'</td>';
          echo '<td>'.$row['phone'].'</th>';
          echo '<td>'.$row['email'].'</td>';
          echo '<td>'.$row['fax'].'</td>';
          echo '<td><button><a href="edit.php?id='.$row['Id'].'">Edit</a></button></td>';
          echo '<td><a onclick="return deleteRec();" href="ajax_delete.php?id='.$row['Id'].'" id="deleteOne">Delete</a></td>';
          echo '<td><a href="view.php?id='.$row['Id'].'" target="_blank">View</a></td>';
          echo '</div>';
      }
  } else {
      echo '<td colspan="9"><h1>No contacts found.</td></h1>';
  }

现在,如果检索到多个数据,我们有多个复选框,我还有一个复选框

<table>
    <tr>
        <td>              
            <input type="checkbox" name="checkAll" id="checkAll"/>
        </td>
        <td colspan="8" align="right">
            <button type="submit" onClick="return massDelete()" name="delete" class="delete" disabled>Delete All</button>
        </td>
    </tr>
</table>

我感到困惑的是,如果我选择了所有检索到的数据复选框,则应自动选择唯一的复选框,即,如果在检索到的10个数据中选择了5个,则不应选择带有id="checkAll"的复选框。相反,如果我选择了所有10个复选框,则只应选择带有id="checkAll"的特定复选框。

监听checkboxeschange事件,如果checked复选框中的length与类别为checkbox1的复选框中length匹配,则checkcheck all复选框。

试试这个:

$('.checkbox1').on('change', function() {
  var bool = $('.checkbox1:checked').length === $('.checkbox1').length;
  $('#checkAll').prop('checked', bool);
});
$('#checkAll').on('change', function() {
  $('.checkbox1').prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="checkbox" name="checkAll" id="checkAll" />Check all
<br>
<input name="checkbox[]" type="checkbox" class="checkbox1" value="">
<br>
<input name="checkbox[]" type="checkbox" class="checkbox1" value="">
<br>
<input name="checkbox[]" type="checkbox" class="checkbox1" value="">
<br>
<input name="checkbox[]" type="checkbox" class="checkbox1" value="">

Fiddle here