JavaScript error - for and if

0

Someone knows how he could perform a alert saying: "attempts are over". In the else could not because it would be repeated every time the script is executed, how could I do something like that?

This is my code.

for (var i = 0; i < 3; i++) {

    var Tuedad = prompt("escribe tu edad");

    if (Tuedad==18) {
        alert("yeahh");
        document.getElementById("demo").innerHTML = tunombre; 
    } else {
        alert("Error");
    }
}
    
asked by simon 23.05.2017 в 08:51
source

2 answers

1

With checking at the end of for that age has not been successful with a flag will suffice:

var bool=false;
for (var i = 0; i < 3 && !bool; i++) {


	var Tuedad = prompt("escribe tu edad");


	if (Tuedad==18) {

	alert("yeahh");
	document.getElementById("demo").innerHTML = tunombre; 
	bool=true;
	}else{

		
    alert("Error");

	}
}
if(!bool){
	alert("intentos se terminaron");
}
    
answered by 23.05.2017 / 08:59
source
2

If I do not understand what you are trying to do the problem is not where to put the message of attempts consumed. That message should be displayed after the for if no result has been correct, ie it should be after the for.

What you have to do is that once an attempt is correct, do not continue asking.

Look at this example:

var tunombre = 'Pepe';

function comprobarEdad() {
  for (var i = 0; i < 3; i++) {
    var Tuedad = prompt("escribe tu edad");
    if (Tuedad === '18') {
      alert("yeahh");
      document.getElementById("demo").innerHTML = tunombre; 
      return;
    }else{
      alert("Error");
    }
  }
  alert('No hay más intentos');
}

comprobarEdad();
<div id="demo"></div>
    
answered by 23.05.2017 в 08:59