dan
dan

Reputation: 41

How can i avoid NaN error at simple form?

I've got simple form that has to return square root of a number. But i get NaN error. As you can see, variable "number" is number-type. What am i doing wrong?

let number = parseInt(document.getElementById('value'));

function myFunction() {
    alert(Math.sqrt(number));
  }
<div class="container">
        
        <form>
            <fieldset>
              <legend>Number squared</legend>
              <p><label >Insert number here: </label><input type="number" id="value"></p>
            </fieldset>
          <p><input type="button" id="button" onclick="myFunction()" value="calculate"></p>
          </form>
    </div>

Upvotes: 0

Views: 1734

Answers (4)

Aman Kumayu
Aman Kumayu

Reputation: 389

You must get your element value inside your function call, otherwise you will get NaN(Not a number), like this:

function myFunction() {
    let number = parseInt(document.getElementById('value').value);
    if(number !== "" && number != undefined && number != null && !isNaN(number)){
        alert(Math.sqrt(number));
    }else{
        alert("Please enter valid number");
    }
}

You can also check for undefined, null and empty string values.

Upvotes: 0

Arun Mohan
Arun Mohan

Reputation: 1227

function myFunction() {
  const number = +document.getElementById('value').value;

  if (isNaN(number)) {
    alert('Please pass in a number') 
    return
  }

  alert(Math.sqrt(number))
}

Upvotes: 1

khan
khan

Reputation: 1464

First, document.getElementById() returns an HTML element. You would have to access the value property by doing document.getElementById().value. Second, the number variable will always be equal to NaN since that line of code is executed first and is never changed.

let value = document.getElementById('value').value // Evaluates to ""
let number = parseInt(value); // Evaluates to NaN

// The number variable is never re-evaluated when the function is invoked
function() {
  alert(Math.sqrt(number));
}

You would have to move that line of code into your function so that the value of number is determined when the function is called, not at the beginning of code execution.

function myFunction() {
  const number = parseInt(document.getElementById('value').value)
  
  if (isNaN(number)) {
    alert('Please pass in a number') 
    return
  }
  
  alert(Math.sqrt(number))
}
<div class="container">
  <form>
    <fieldset>
      <legend>Number squared</legend>
      <p><label>Insert number here: </label><input type="number" id="value"></p>
    </fieldset>
    <p><input type="button" id="button" onclick="myFunction()" value="calculate"></p>
  </form>
</div>

Upvotes: 1

Prakhar Londhe
Prakhar Londhe

Reputation: 1471

It is because document.getElementById() returns the element itself and not the value. You need to get the value of the input to parse it as integer.

Change the code to parseInt(document.getElementById('value').value);

Upvotes: 0

Related Questions