MikeMichaels
MikeMichaels

Reputation: 494

Switch Statement - Multiple results for single case

I have this page:

var count = 0;

function switchStatement() {
  var text;
  var answers = document.getElementById("userInput").value;
  switch (answers) {
    case "":
      text = (count > 0) ? "You didn't type anything." : "Please type something down...";
      if (count < 1)
        count++;
      else
        count = 0;
      break;
    default:
      text = "Good job!";
  }
  document.getElementById("feedback").innerHTML = text;
  document.getElementById("userInput").value = "";
}
<p>Please write something down and press "enter".</p>

<input id="userInput" type="text" onKeyDown="if(event.keyCode==13) switchStatement();">

<p id="feedback"></p>

When the user doesn't type anything before pressing "enter", (that's case = "";), a message will show up. If he does the same thing again, a different message will show up. If he does it a third time, it will loop back to the first message.

How can I add more messages to avoid having such a small loop? Say, if I wanted to have 5 different messages for when the user doesn't type anything, what should I change in my code?

Upvotes: 2

Views: 155

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

You could use an array of messages :

var messages = ["message 1...", "message 2...", "message 3...", "message 4...", "message 5..."]

Then use the count variable as the index of this array to show the messages one after other.

NOTE: You must init the count to the default value 0 in case the user typed something so the next empty submit will show the first message in index 0.

var count = 0;
var messages = ["message 1...", "message 2...", "message 3...", "message 4...", "message 5..."];

function switchStatement() {
  var text;
  var answers = document.getElementById("userInput").value;

  switch (answers) {
    case "":
      text = messages[count];
      count = count < messages.length - 1 ? count + 1 : 0;
      break;
    default:
      text = "Good job!";
      count = 0;
  }
  document.getElementById("feedback").innerHTML = text;
  document.getElementById("userInput").value = "";
}
<p>Please write something down and press "enter".</p>

<input id="userInput" type="text" onKeyDown="if(event.keyCode==13) switchStatement();">

<p id="feedback"></p>

Upvotes: 2

Related Questions