0

it seems to think ttinput is a string when I console.log the variable it says "". All else seems to working I just can't figure out how to have ttinput as a number.

document.getElementById("enter").addEventListener("click", ttcalc)
var ttinput = document.getElementById("table").value;
var ttoutput;


function ttcalc(){

        var display = "";

        for(var i = 1; i <= 12; i++){

            ttoutput = ttinput * i;
            display += ttinput + "*" + i + "=" + ttoutput + "<br>"
            console.log(ttoutput, ttinput, i);

        }

    document.getElementById("output").innerHTML = display;

}

this is my html

    <form>
            <h1>Enter what times table you wish to see</h1>
            <input type="number" id="table"><br>
        </form>

        <button id="enter">Show Times Table</button>
    </div>
narom391
  • 1
  • 1

1 Answers1

0

The problem is that the value of

var ttinput = document.getElementById("table").value;

is read on page load (while the input field is empty). If you move that line of code inside your function it will read the value of the input field after the button is clicked.


If you want to be sure the value entered is a number you can use the parseInt() function and then check if the result is a number with the isNaN() function like this:

var ttinput = parseInt(document.getElementById("table").value);

and then use isNaN():

if( !isNaN(ttinput) ) {
    // ttinput is a number
} else {
    // ttinput is not a number
}

More here: parseInt and isNaN.


Check example below:

document.getElementById("enter").addEventListener("click", ttcalc)

function ttcalc() {
  var ttinput = parseInt(document.getElementById("table").value);
  var ttoutput;
  var display = "";

  if( !isNaN(ttinput) ) {
    for(var i = 1; i <= 12; i++) {
      ttoutput = ttinput * i;
      display += ttinput + "*" + i + "=" + ttoutput + "<br>"
      console.log(ttoutput, ttinput, i);
    }
    document.getElementById("output").innerHTML = display;
  } else {
    console.log("value is not a number");
  }
}
<button id="enter">Enter</button>
<input type="text" id="table" value="">
<div id="output"></div>
Ivan86
  • 5,695
  • 2
  • 14
  • 30