0
Thanks

A few words of thanks would be greatly appreciated.

HTML - For loop with if and else

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>
0
Thanks

A few words of thanks would be greatly appreciated.

Ask a question
CCM is a leading international tech website. Our content is written in collaboration with IT experts, under the direction of Jeff Pillou, founder of CCM.net. CCM reaches more than 50 million unique visitors per month and is available in 11 languages.

Related

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).

0 Comments