vendredi 9 novembre 2018

jQuery If Else Statement printing out to many times

I'm trying to have so if a user enters there name and a number 1-20, it will print their name that many times. Right now, I have it so it prints out the correct number of times, but when you print out the error code, it prints 20 times instead of once. This is due to the for loop. I'm just not sure how to restructure the loop.

For example: J, 32 Answer: Please enter a number 1-20

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" ></script>

    <script type="text/javascript">
  function greetMe() {
    var name = document.getElementById('txtName').value;
    var nr   = document.getElementById('txtNmr').value;

    for (var counter = 0; counter < nr; counter = counter + 1) {
      if (nr > 1 && nr < 20){
        $('#greetings').append("Hello, " + name + "<br />");
      }
      else{
        $('#errors').append("Please Enter A Number Between 1 and 20");
        //$('#errors').addClass('highlight');
      }
    }
  } 
    </script>

HTML:

</head>
<body>
<p>Type in your name</p>
<input type="text" id="txtName">
<p>Enter a numner 1-20.</p>
<input type="text" id="txtNmr">
<input type="button" value="Greet Me!" onclick="greetMe()">
<hr>
<div id="greetings">
  <!-- Section to output the greeting -->
</div>
<div id="errors">
  <!-- Section to output the greeting -->
</div>
</body>
</html>

Aucun commentaire:

Enregistrer un commentaire