2015-12-23 63 views
0

我正在尋找邏輯,我有一些數據列表中的while循環使用php獲取,如下所示。選擇一個複選框當選擇所有chekboxes

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"的特定複選框。

+3

試試這個:( 'checkbox1 ')。'$上(' 改變',如果函數(){ ($ ('.checkbox1:checked')。length === $('。checkbox1')。length){ $('#checkAll')。prop('checked',true); } }); (''checkbox1')。prop('checked',this.checked()。'(''checkbox1')。 ); });' – Rayon

+2

@RayonDabre讓它成爲答案... – epascarello

+0

檢查/取消選中所有複選框的第二部分已經完美完成。這樣可行。但第一部分依然存在。謝謝你的努力先生。 –

回答

1

change事件checkboxes和如果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