Anna Bannanna
Anna Bannanna

Reputation: 135

How to create while loop with alert and prompt to avoid empty input?

I want to create a while loop to avoid empty input. Here's my code, I want it to loop so that the user gets the same alert and then prompt window until he/she writes a name/username. Any ideas on what I'm doing wrong and how to fix it?

<script type="text/javascript">
confirm("Wanna play?");
var name = prompt("What's your name?");
while (name.length == 0) {
    alert("Please enter your name!");
    prompt("What's your name?");
}
else {
    document.write("Welcome to my game " + name + "!" + "<br>");
}
</script>

Upvotes: 1

Views: 9783

Answers (4)

SurajDeveloper
SurajDeveloper

Reputation: 1

Use This

var name = prompt("What's your name?");
while (name.length == 0 || name == "null" || name == null) {
    name = prompt("What's your name");
}

Upvotes: 0

Ivo Nogueira
Ivo Nogueira

Reputation: 1

See If this does what you're looking for!

confirm("Wanna play?");
var name = prompt("What's your name?");
while (name.length == 0) {
    name = prompt("Please, insert a name to proceed!");
}
document.write("Welcome to my game " + name + "!" + "<br>");

Upvotes: 0

Mohit Bhardwaj
Mohit Bhardwaj

Reputation: 10083

@Renan suggested it right. Still, if you need the current code to work, you can try this:

<script type="text/javascript">
confirm("Wanna play?");
var name = prompt("What's your name?");
while (name.length == 0) {
    alert("Please enter your name!");
    name = prompt("What's your name?");
}
document.write("Welcome to my game " + name + "!" + "<br>");
</script>

There are some errors in your code/logic:

  1. Why is there else after while? else is used with if clause only.
  2. You are asking for the name in the while loop, but not assigning it to the name variable. If you do not assign to name, how would the name variable get updated and cause the while loop to exit?

Upvotes: 4

Geeky Guy
Geeky Guy

Reputation: 9399

Never abuse prompt, alert and confirm in your pages.

I could write a lot about this but I will just leave this image here.

Users can easily silence your attempts to call their attention via dialogs, so any extra effort you spend on that is wasted.

Upvotes: 3

Related Questions