I want to know why if
and else if
are not working.
I know there are many similar questions out there but they are mostly about jquery and php, not pure javascript. There's one question very similar to mine:
JavaScript - Using "checked/unchecked checkbox" as "IF ELSE condition statement"
But even there I copied the code, and the if
and else if
statements don't work.
var label = document.getElementsByTagName("label");
var show = () => {
var c1h = document.getElementById("c1h");
var th = document.getElementById("th");
var c2h = document.getElementById("c2h");
var c3h = document.getElementById("c3h");
var c1 = document.getElementById("c1");
var t = document.getElementById("t");
var c2 = document.getElementById("c2");
var c3 = document.getElementById("c3");
if (c1h.checked === true) {
c1.style.visibility = "visible";
} else if (th.checked === true) {
t.style.visibility = "visible";
} else if (c2h.checked === true) {
c2.style.visibility = "visible";
} else if (c3h.checked === true) {
c3.style.visibility = "visible";
}
}
label.onclick = show;
p {
width: 250px;
}
label {
display: block;
}
.tick,
.cross {
width: 20px;
height: 20px;
float: right;
visibility: hidden;
}
<h2>What is a snail?</h2>
<form>
<label>A: Insect<input id="c1h" name="assassin"
class="radio" type="radio" checked="checked" /><img id="c1"
class="cross" src="images/cross.png" /></label>
<br />
<label>B: Mollusc<input id="th" name="assassin"
class="radio" type="radio" /><img id="t" class="tick"
src="images/tick.png" />
</label>
<br />
<label>C: Amphibian<input id="c2h" name="assassin"
class="radio" type="radio" /><img id="c2" class="cross"
src="images/cross.png" /></label>
<br />
<label>D: Mammal<input id="c3h" name="assassin"
class="radio" type="radio" /><img id="c3" class="cross"
src="images/cross.png" /></label>
</form>
if any of the if
or else if
statements are true
then the corresponding image should get displayed, but it does not.