Search code examples
arraysloopsfor-loopif-statementtextbox

Why are negative integers not registering in my text box?


I've been struggling since since morning trying to figure out what's wrong with my code. I tried looking up questions on here but I couldn't find anything to help. My goal with this code is to create a loop and list all the integers entered in the text field for all numbers greater than 0 (i.e. if 7 is entered, then 01234567 would appear) which I was able to figure out. However, my second goal is to make it so that if a negative number such as -1 a text appears saying "No valid number was enterned, no negatives can be sumbitted." The problem is that if I enter a negative number, nothing happens. I believe the problem lies in 'if (test1 < 0)' because if I change 0 to a positive number like 3, the text appears.

Any help would be appreciated, thank you all!

<html>
<body>

<h2></h2>


<form action="">
<input type="text" name="test1" id=t1><br>

<input type="button" value="Enter Number" onclick="EnterNumber()">

</form>

<p id="result"></p>

<script>
function EnterNumber() {
var test1 = document.getElementById("t1").value;
var text = "";
var i;


for (i = 0; i <= test1; i++) {
if (test1 < 0){
    document.write("No valid number was enterned, no negatives can be sumbitted.");
    break;
  }


  text += i + "<br>";
}




document.getElementById("result").innerHTML = text;
}
</script>

</body>
</html>

Solution

  • If test1 is less than zero, the loop will never run, so the negative check won't happen.

    Do the check before the loop.

    Try this code:

    <script>
    function EnterNumber() {
    var test1 = document.getElementById("t1").value;
    var text = "";
    var i;
    
    if (test1 < 0){
        text = "No valid number was entered, no negatives can be submitted."
        //document.write("No valid number was entered, no negatives can be submitted.");
      }
    
    for (i = 0; i <= test1; i++) {
      text += i + "<br>";
    }
    
    document.getElementById("result").innerHTML = text;
    }
    </script>