HTML - For loop with if and else

July 2017

Issue


I must create a pop-up that will be triggered upon answering a question.
E.g 3+1 =
My problem comes when the user is anything other than the number 4, the question will be asked again (in a loop), until the right answer is given.


<script type="text/javascript"> 
nom = window.prompt("nom ?"); 
alert("merci "+nom+ " bienvenue!"); 
</script> 

<script type="text/javascript"> 

nb = window.prompt("3+1 ?"); 

if (nb==4) { 
alert ("bravo") 
} 
else { nb!=4 
nb = window.prompt("3+1 ?"); 
} 

Solution


Do not use a for loop, but a while.


Replaces your second script with this:

<script type="text/javascript">
   nb = 0;

   while (nb != 4){
      nb = window.prompt("3+1 ?");
   }
   if (nb == 4){
      alert("Bravo !");
   }
</script>

Related


Published by aakai1056. Latest update on October 31, 2011 at 08:53 AM by aakai1056.
This document, titled "HTML - For loop with if and else ," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (ccm.net).