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("Wele to my game " + name + "!" + "<br>");
}
</script>
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("Wele to my game " + name + "!" + "<br>");
}
</script>
Share
Improve this question
edited Jan 20, 2017 at 16:47
Adam Michalik
9,96513 gold badges75 silver badges107 bronze badges
asked Jun 8, 2016 at 16:50
Anna BannannaAnna Bannanna
1353 silver badges10 bronze badges
0
4 Answers
Reset to default 4@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("Wele to my game " + name + "!" + "<br>");
</script>
There are some errors in your code/logic:
- Why is there
else
afterwhile
?else
is used withif
clause only. - You are asking for the name in the
while
loop, but not assigning it to thename
variable. If you do not assign toname
, how would thename
variable get updated and cause thewhile
loop to exit?
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.
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("Wele to my game " + name + "!" + "<br>");
Use This
var name = prompt("What's your name?");
while (name.length == 0 || name == "null" || name == null) {
name = prompt("What's your name");
}