Biasanya Anda juga ingin kotak centang master tidak dicentang jika setidaknya 1 kotak centang budak tidak dicentang dan dicentang jika semua kotak centang budak dicentang:
/**
* 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');
}
});
}
Dan jika Anda ingin mengaktifkan kontrol apa pun (misalnya Remove All
tombol atau Add Something
tombol), saat setidaknya satu kotak centang dicentang dan nonaktifkan ketika tidak ada kotak centang yang dicentang:
/**
* 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');
}
}