Among the 3 toggle button if all of them is selected then automatically one toggle should switch off. I shouldn’t not be able to select all the three.
I tried to go with setInterval which check the conditions every second but it didn’t work.
When setInterval get control,it eventually switch offs all the buttons
let zval, aval, asval;
const zaid = document.getElementById('zaid')
const anas = document.getElementById('anas')
const asgar = document.getElementById('asgar')
zval = zaid.checked;
aval = anas.checked;
asval = asgar.checked;
zaid.addEventListener('click', () => {
if (zval == false) {
zval = true
zaid.checked = true;
} else {
zval = false
zaid.checked = false;
}
})
anas.addEventListener('click', () => {
if (aval == false) {
aval = true
anas.checked = true;
} else {
aval = false
anas.checked = false;
}
})
asgar.addEventListener('click', () => {
if (asval == false) {
asval = true
asgar.checked = true;
} else {
asval = false
asgar.checked = false;
}
})
let arr = [zaid, anas, asgar];
setInterval(check, 1000);
function check() {
let arr2 = [zval, aval, asval]
if (zval == true && aval == true && asval == true) {
let val = Math.floor(Math.random() * 3);
arr2[val] = false;
arr[val].checked = false;
console.log(arr2)
} else {
console.log('else')
}
}
<div class="container">
<div class="box">
<input type="radio" name="" id="zaid">
<label for="zaid">Zaid</label>
</div>
<div class="box">
<input type="radio" name="" id="anas">
<label for="anas">Anas</label>
</div>
<div class="box">
<input type="radio" name="" id="asgar">
<label for="asgar">Asgar</label>
</div>
</div>
2
Answers
1- radio buttons are not checkboxs, use
<input type="checkBox"
2- prefer to use
change
event instead ofclick
3- there is no needs to use
setInterval()
method, just un-check last checkbox if ther is more than two.You can simply do this ?
So if I understand you correctly you would only like a max of 2 items to be clicked at a time… So I would implement it like this.
Basically you have an array to track the order of how the buttons were clicked and the 1st one will automatically be unchecked once 3 are checked.
See code below (HTML left unchanged):