Skip to content

Instantly share code, notes, and snippets.

@alantsai
Last active February 12, 2019 05:45
Show Gist options
  • Save alantsai/8221123 to your computer and use it in GitHub Desktop.
Save alantsai/8221123 to your computer and use it in GitHub Desktop.
選取所有checkbox和判斷是否全部checkbox已經被勾選
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="選取所有checkbox和判斷是否全部checkbox已經被勾選" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<form>
<table>
<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>
</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");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment