-4

I'm fairly new to javascript and am trying to make something that allows people to access information about something that I like. E.g MLP or HoO, but my else if conditions seem to be ignored after the first else if.

var infoChoice = prompt("MLP, PJ&tO, or HoO?")
if (infoChoice != "MLP") {
    if (infoChoice != "PJ&tO") {
        if (infoChoice != "HoO") {
            confirm(infoChoice + " is not a valid option.")
        }
    }
} else if (infoChoice = "MLP") {
    confirm("MLP stands for My Little Pony. The 4th generation of MLP, known as MLP:FIM, (My Little Pony: Friendship is Magic) is by far the most well-known and beloved generation.")
} else if (infoChoice = "HoO") {
    confirm(infoChoice + " has been registered successfully.")
}

When I run it and search MLP it does fine, but any other "valid" option doesn't work. Please help, this is extremely frustrating.

Sushil
  • 2,837
  • 4
  • 21
  • 29

3 Answers3

4

The mistake is:

if (infoChoice = "MLP") 

should be:

else if (infoChoice == "MLP")

else if (infoChoice == "HoO")

You are comparing values here, not assigning

RobG
  • 142,382
  • 31
  • 172
  • 209
Andrey
  • 2,659
  • 4
  • 29
  • 54
1

If you have a limited set of possibilities, use a switch statement:

switch(prompt("MLP, PJ&tO, or HoO?").toLowerCase()) {
case "mlp":
    alert("MLP stands for My Little Pony. The 4th generation of MLP, known as MLP:FIM, (My Little Pony: Friendship is Magic) is by far the most well-known and beloved generation.");
    break;
case "hoo":
    alert(infoChoice + " has been registered successfully.");
    break;
case "pj&to":
    // do something?
    break;
default:
    alert("That is not a valid option.");
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

My java is a bit rusty, but I think trying else if (infoChoice.equals("MLP")) instead of using the == operator. The reason is that == is a reference comparator, while .equals compares for value.

Check out this How do I compare strings in Java?

Community
  • 1
  • 1
nguyminh
  • 21
  • 3
  • [What's the difference between JavaScript and Java?](http://stackoverflow.com/questions/245062/whats-the-difference-between-javascript-and-java) – Alexei Levenkov Sep 08 '15 at 23:31
  • @AlexeiLevenkov While it's tagged javascript the question clearly says "Java" so this is valid. – Uncle Iroh Sep 08 '15 at 23:33
  • 1
    @UncleIroh Then perhaps the link should be thrown at the OP ;) – Niet the Dark Absol Sep 08 '15 at 23:34
  • 1
    I didn't even realize the question was for javascript. My apologies. The question does say "java" in the main body. In that case, Andrey's answer is correct. Use `==` – nguyminh Sep 08 '15 at 23:34
  • @nguyminh the question has been edited now to say javascript, the java/javascript mixups happen quite a lot in questions from people new to JS. – Mousey Sep 09 '15 at 00:33