HTML 代码:
<input type="checkbox" id="allChecked" onclick="setAllChecked(this.checked)" />
<input type="checkbox" name="hobby" onclick="setCheckedAll()" value="1" />
JavaScript 脚本:
/**
* 设置“全选”或“全反选”
*/
var setAllChecked = function(isAllChecked){
if(isAllChecked) {
$('input[name=hobby]').prop("checked", true);
} else {
$('input[name=hobby]').prop("checked", false);
}
}
/**
* 设置“选全”或“反选全”
*/
var setCheckedAll = function(){
var hobbyCount = $('input[name=hobby]').length;
var checkedCount = $('input[name=hobby]:checked').length;
if(hobbyCount === checkedCount) {
$('#allChecked').prop("checked", true);
} else {
$('#allChecked').prop("checked", false);
}
}