<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" data-semver="1.9.1" data-require="jquery@*"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<form>
<table>
<tbody>
<tr>
<th>
<input type="checkbox" id="checkAll" />
</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>
<input type="checkbox" name="chkPerson" />
</td>
<td>
Jack
</td>
<td>
18
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="chkPerson" />
</td>
<td>
Alan
</td>
<td>
26
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
$(function(){
$('#checkAll').change(function() {
//get all checkbox which want to change
var checkboxes = $(this).closest('form').find('input[name="chkPerson"]:checkbox');
if($(this).is(':checked')) {
checkboxes.prop('checked', 'checked');
} else {
checkboxes.removeAttr('checked');
}
});
$('input[name="chkPerson"]').change(function(){
checkOrRemoveCheckAll();
});
});
function checkOrRemoveCheckAll(){
if($('input[name="chkPerson"]:checked').length == $('input[name="chkPerson"]').length)
{
$('#checkAll').prop("checked", "checked");
}
else
{
$('#checkAll').removeAttr("checked");
}
}
/* Styles go here */
#選取所有checkbox和判斷是否全部checkbox已經被勾選
1. 勾選/取消勾選 全部勾選checkbox的時候 勾選/取消勾選 所有對應的checkbox
2. 當所有對應checkbox有別勾選的時候, 全部勾選checkbox 也要被勾選
[部落格網址](http://www.dotblogs.com.tw/alantsai/archive/2014/01/02/jquery_checkbox_snippet.aspx)