0

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.

3
  • To clarify the below answers, ALL form elements are ASCII strings. If you need to get an integer value, you need to do a conversion. Commented Oct 26, 2015 at 18:25
  • a is the element, not the input value. Try parseInt(a.value, 10) Commented Oct 26, 2015 at 18:26
  • And better to set innerHTML to b.toString() Commented Oct 26, 2015 at 18:27

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Cleaner even would be a = parseInt(document.getElementById("sidea").value), 10); (Reassigning variable a to completely different variable type is not so clean).
@wintvelt now its clean.
since its not HTML, you could use textContent, its faster and safer.. *although i don't see how this function could return anything dangerous in the first place

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.