cCe.jbc
cCe.jbc

Reputation: 117

JavaScript returns NaN even if input is an integer

I am typing an integer in the input box and it still returns 'NaN'.

function goldenFunctiona() {
  a = document.getElementById("sidea");
  parseInt(a, 10);
  b = ((a + a) * (Math.pow(5, 0.5))) / 2;
  document.getElementById("b").innerHTML = b;
}
<div id="top">
  <p>Side a =</p>
  <input id="sidea" type="number">
  <button id="button" onclick="goldenFunctiona()" type="button">Find side b</button>
  <p id="b"></p>
</div>

I don't know what's going wrong but it's probably something really simple. Thanks in advance.

Upvotes: 0

Views: 746

Answers (1)

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

document.getElementById("sidea") doesn't returns a number, but an element. Use document.getElementById("sidea").value instead to get the element value.

So:

function goldenFunctiona() {
    var sideaVal = document.getElementById("sidea").value;

    var a = parseInt(sideaVal , 10); // Get parseInt's return value or 'a' will still be a string
    var b = ((a + a) * (Math.pow(5, 0.5))) / 2;

    document.getElementById("b").innerHTML = b;
}

Upvotes: 4

Related Questions