0

I'm very new to JavaScript and was asked to complete a nested if question. I found that I'm having trouble executing the second part. When you choose 'B', it's all good but when you choose 'G', you only get to type in a variable for the first statement and then it justs ends there.

Also, is it possible to write multiple nested if statements? As in let's say in the code below, after I told them "Work sucks...", can I continue to prompt the user to enter a variable?

Thank you!

<!DOCTYPE>
<html>
<head>
    <title>Hello</title>
    <script type="text/javascript">
      var ans;
      var b1;
      var g1;

      ans = prompt ("How are you feeling?\n'B' for Bad | 'G' for Good");

      if (ans == 'B')
      {
        b1 = prompt ("I'm sorry ... 'W'.\nIf not, type 'E'");

        if (b1 == 'W')
        {
          window.alert ("Work sucks ...."); 
        }
        else if (b1 == 'E')
        {
          window.alert ("Here's ..");
        }
      }
      else if (ans == 'G')
      {
        g1 == prompt("That's great! I hope you have a fantastic day ahead!\n'C' to Continue | 'R' to Exit");
        if (g1 == 'C')
        {
          window.alert ("...");
        }
        else if (g1 == 'R')
        {
          window.alert ("Goodbye. Have a lovely day!");
        }
      }
    </script>
</head>
<body>
</body>
</html>
2
  • An if statement is not a loop, but a condition! Commented Jul 12, 2018 at 9:26
  • @MarkFrankli ops, sorry, that's a typo! Commented Jul 12, 2018 at 9:26

1 Answer 1

1

There was a typo in your code. For assignment, it has to be g1 = and not g1 ==

var ans;
var b1;
var g1;

ans = prompt("How are you feeling?\n'B' for Bad | 'G' for Good");

if (ans == 'B') {
  b1 = prompt("I'm sorry ... 'W'.\nIf not, type 'E'");

  if (b1 == 'W') {
    window.alert("Work sucks ....");
  } else if (b1 == 'E') {
    window.alert("Here's ..");
  }

} else if (ans == 'G') {
  g1 = prompt("That's great! I hope you have a fantastic day ahead!\n'C' to Continue | 'R' to Exit");

  if (g1 == 'C') {
    window.alert("...");

  } else if (g1 == 'R') {
    window.alert("Goodbye. Have a lovely day!");
  }
}

Sign up to request clarification or add additional context in comments.

2 Comments

Oh dear, thank you! I don't know how I could've missed that!
@Maya - No worries. Can happen :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.