I was working on a project in that some situation comes out that:
- optionC is by default checked When someone checked optionA and
optionB then optionC should unchecked When someone checked optionC
after it unchecked then optionB should unchecked When someone check
ed optionB after it unchecked then optionA should unchecked— Thats All!
Here is my Code:
var optionA = document.getElementById("optionA");
var optionB = document.getElementById("optionB");
var optionC = document.getElementById("optionC");
optionC.checked = true;
[ optionA, optionB, optionC ].forEach(function(option) {
option.addEventListener("click", function() {
if(optionA.checked && optionB.checked){
optionC.checked = false;
}
else if(optionA.checked && optionB.checked && optionC.checked){
optionB.checked = false;
}
//Here also Code is missing
else{
optionC.checked = true;
}
});
});
<div>
<input type="checkbox" id="optionA" name="optionA" />
<label for="optionA">Option A</label>
<input type="checkbox" id="optionB" name="optionB" />
<label for="optionB">Option B</label>
<input type="checkbox" id="optionC" name="optionC" />
<label for="optionC">Option C</label>
</div>
But I am facing an Error That after optionC is unchecked user is not able to check it again
2
Answers
Your code was wrong because you should also refer to the data of who the
checkbox
fired the click event, I fixed the code by usinge.target
to check who fired the eventJust to clarify objective:
#optionC
ischecked
by default#optionA
and#optionB
✥ are checked by the user,#optionC
is unchecked#optionB
is checked by the user,#optionA
is unchecked#optionC
is checked by the user,#optionB
is unchecked✥
#optionB
must be checked before#optionA
is checkedDetails are commented in example