Hi I need help with my code so basically I’m making a project where when you select the checkboxes and it will show a text result. I was able to create a if else condition but I’m getting a problem with ,it is showing all the text if all checkboxes are checked.
here’s my code
<!DOCTYPE html>
<html>
<body>
<p>Display some text when the checkbox is checked:</p>
<label for="myCheck">Checkbox:</label>
<input type="checkbox" id="myCheck" onclick="myFunction()">
<label for="myCheck">Checkbox2:</label>
<input type="checkbox" id="myCheck1" onclick="myFunction()">
<p id="text" style="display:none"> both</p>
<p id="text2" style="display:none">ch1!</p>
<p id="text3" style="display:none">ch2!</p>
<script>
function myFunction() {
var checkBox = document.getElementById("myCheck");
/*should only show text "both"*/
if (checkBox.checked == true && myCheck1.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
/* show text "ch1"*/
if (myCheck.checked == true){
text2.style.display = "block";
} else {
text2.style.display = "none";
}
/* show text "ch2"*/
if (myCheck1.checked == true){
text3.style.display = "block";
} else {
text3.style.display = "none";
}
}
</script>
</body>
</html>
I tried hiding the other texts by putting it like this
if (checkBox.checked == true && myCheck1.checked == true){
text.style.display = "block";
text2.style.display = "none";
text3.style.display = "none";
} else {
text.style.display = "none";
but it still didn’t work I really need help thank you.
2
Answers
Start by hiding all three, then enable them as needed. See the code snippet:
The best answer is provided by @Ray Wallace,my answer is not easy to understand ,you can try it.