HTML - For loop with if and else

December 2016

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 :

This document entitled « HTML - For loop with if and else  » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.