通常,如果至少选中了一个从属复选框,那么您也希望不选中主复选框,而如果选中了所有从属复选框,则希望取消复选框:
/**
* Checks and unchecks checkbox-group with a master checkbox and slave checkboxes
* @param masterId is the id of master checkbox
* @param slaveName is the name of slave checkboxes
*/
function checkAll(masterId, slaveName) {
$master = $('#' + masterId);
$slave = $('input:checkbox[name=' + slaveName + ']');
$master.click(function(){
$slave.prop('checked', $(this).prop('checked'));
$slave.trigger('change');
});
$slave.change(function() {
if ($master.is(':checked') && $slave.not(':checked').length > 0) {
$master.prop('checked', false);
} else if ($master.not(':checked') && $slave.not(':checked').length == 0) {
$master.prop('checked', 'checked');
}
});
}
如果要启用任何控件(例如Remove All
按钮或Add Something
按钮),则至少选中一个复选框,而未选中则禁用:
/**
* Checks and unchecks checkbox-group with a master checkbox and slave checkboxes,
* enables or disables a control when a checkbox is checked
* @param masterId is the id of master checkbox
* @param slaveName is the name of slave checkboxes
*/
function checkAllAndSwitchControl(masterId, slaveName, controlId) {
$master = $('#' + masterId);
$slave = $('input:checkbox[name=' + slaveName + ']');
$master.click(function(){
$slave.prop('checked', $(this).prop('checked'));
$slave.trigger('change');
});
$slave.change(function() {
switchControl(controlId, $slave.filter(':checked').length > 0);
if ($master.is(':checked') && $slave.not(':checked').length > 0) {
$master.prop('checked', false);
} else if ($master.not(':checked') && $slave.not(':checked').length == 0) {
$master.prop('checked', 'checked');
}
});
}
/**
* Enables or disables a control
* @param controlId is the control-id
* @param enable is true, if control must be enabled, or false if not
*/
function switchControl(controlId, enable) {
var $control = $('#' + controlId);
if (enable) {
$control.removeProp('disabled');
} else {
$control.prop('disabled', 'disabled');
}
}