Sarah Marie Sarah Marie - 23 days ago 7
Javascript Question

Why isn't this javascript prompt working?

I am trying to make images of the specific candy pop up when you type in its name but only Ghirardelli works.

<p id="chocolate"></p>
<img src="hershey.jpg" id="pic">
<script>
var y = prompt("What would you like to see a picture of?");
if (y == "Hershey")
{
document.getElementById("chocolate").innerHTML="Hershey";
}
if (y == "Reeses")
{
document.getElementById("chocolate").innerHTML="Reeses";
document.getElementById("pic").src="reeses.jpg";
}
if (y == "Ghiradelli")
{
document.getElementById("chocolate").innerHTML="Ghiradelli";
document.getElementById("pic").src="ghiradelli.jpg";
}
else
{
document.getElementById("chocolate").innerHTML="Please choose one of these three things: <ul><li>Hershey</li><li>Reeses</li><li>Ghiradelli</li></ul>";
document.getElementById("pic").src="x.svg";
}
</script>

Answer

That's because you only have one else in the whole thing. The first two if statements are operating independently. They work, but the final if is not true when they are, so the logic in the else overwrites anything the first two if's did.

Just make the rest else if.

var y = prompt("What would you like to see a picture of?");
if (y == "Hershey")
{
    document.getElementById("chocolate").innerHTML="Hershey";
}
else if (y == "Reeses")
{
    document.getElementById("chocolate").innerHTML="Reeses";
    document.getElementById("pic").src="reeses.jpg";
}
else if (y == "Ghiradelli")
{
    document.getElementById("chocolate").innerHTML="Ghiradelli";
    document.getElementById("pic").src="ghiradelli.jpg";
}
else
{
    document.getElementById("chocolate").innerHTML="Please choose one of these three things: <ul><li>Hershey</li><li>Reeses</li><li>Ghiradelli</li></ul>";
    document.getElementById("pic").src="x.svg";
}