<input class="group-red" type="checkbox"> A
<input class="group-red" type="checkbox"> B
<input class="group-red" type="checkbox"> c
<input class="group-blue" type="checkbox"> D
Code (JavaScript)
function detectCheckable(clickedTarget) {
let groupRedChecked = false;
let groupBlueChecked = false;
document.querySelectorAll('.group-red').forEach((item) => {
if (item.checked === true) {
groupRedChecked = true;
return true;
}
});
document.querySelectorAll('.group-blue').forEach((item) => {
if (item.checked === true) {
groupBlueChecked = true;
return true;
}
});
if (groupRedChecked === true && clickedTarget.classList.contains('group-blue')) {
document.querySelectorAll('.group-blue').forEach((item) => {
item.checked = false;
});
}
if (groupBlueChecked === true && clickedTarget.classList.contains('group-red')) {
document.querySelectorAll('.group-red').forEach((item) => {
item.checked = false;
});
}
}
document.addEventListener('click', (event) => {
let thisTarget = event.target;
if (thisTarget.type === 'checkbox') {
detectCheckable(thisTarget);
}
});