Search code examples
javascriptfor-loopif-statementcountergetelementbyid

Javascript: Looping to any number with even/odd descriptions. Why does it just record the user input?


I need to have the loop in this script count up to any number the user inputs.

It accurately describes the user input, but doesn't loop and count up to it.

How do I go about fixing this? Should I be coding it differently?

I am very new to javascript, and coding in general, any advice would be much appreciated!

Here is what I have so far:

function clickAlert2() {
  var whatNum = document.getElementById("userEnterNum").value;
  for (var i = 1; i <= whatNum; i++) {
    if (i % 2 === 0)  
      document.getElementById("evenOddList").innerHTML = i + ". National Gamers - EVEN <br>";
    else if (i % 2 === 1)
      document.getElementById("evenOddList").innerHTML = i + ". National Gamers - ODD <br>";
  }
}  

Solution

  • Now I understood what you want. Here is the code. Just copy and paste.

    <input type="text" id="userEnterNum">
    <button type="button"
            onclick="clickAlert2()">Test
    </button>
    <div id="evenOddList"></div>

    function clickAlert2() {
      var whatNum = document.getElementById("userEnterNum").value;
      var whatNum = parseInt(whatNum);  // this will parse the string to a number
      for (var i = 1; i <= whatNum; i++) {
       if (i % 2 == 0) {
          document.getElementById("evenOddList").innerHTML += i + ". National Gamers - EVEN <br>";
        } else {
          document.getElementById("evenOddList").innerHTML += i + ". National Gamers - ODD <br>";
        }
      }
    }