简体   繁体   中英

How do I stop the second prompt from appearing until the first if/else condition is satisfied? (Start Page for a game)

If the user name is not entered, the age prompt still comes up, I want the whole prompt to terminate if the user name is not entered, basically, when it says "You cannot proceed without the name" after that the prompt asking for the age still appears, I don't want that to happen.

Here is my code:

</style>

<body>
<h1>Welcome to </h1>
<h2> Hangman </h2>
<div class="wrapper">
  <button onclick="myFunction()">Let's start</button>
</div>

<script>
  function myFunction() {
  let person = prompt("Please enter your name", "Marium");
  if (person == null || person == "") {
  alert("You cannot proceed without entering the name");
  } 
  else {
  alert("Hello " + person);
  }
   
   let age= prompt("Please enter your age"); 
  if (age<16) { 
   alert("User below 16 cannot proceed");
   }
    else {
   window.location.href= "sample.html";
   }
}

You just need to insert a return before the alert in the if statement relative to the missing username case:

 function myFunction() { let person = prompt("Please enter your name", "Marium"); if (person == null || person == "") { return alert("You cannot proceed without entering the name"); } else { alert("Hello " + person); } let age = prompt("Please enter your age"); if (age < 16) { alert("User below 16 cannot proceed"); } else { window.location.href = "sample.html"; } }
 <h1>Welcome to </h1> <h2> Hangman </h2> <div class="wrapper"> <button onclick="myFunction()">Let's start</button> </div>

Add a return; after

alert("You cannot proceed without entering the name");

Code:

<body>
<h1>Welcome to </h1>
<h2> Hangman </h2>
<div class="wrapper">
  <button onclick="myFunction()">Let's start</button>
</div>

<script>
  function myFunction() {
  let person = prompt("Please enter your name", "Marium");
  if (person == null || person == "") {
  alert("You cannot proceed without entering the name");
  return;
  } 
  else {
  alert("Hello " + person);
  }
   
   let age= prompt("Please enter your age"); 
  if (age<16) { 
   alert("User below 16 cannot proceed");
   }
    else {
   window.location.href= "sample.html";
   }
}
</style>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM