通常,如果至少有 1 个从复选框未被选中,您还希望主复选框未被选中,如果所有从复选框都被选中,则被选中:
/**
* 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');
}
}