ReinForce
ReinForce

Reputation: 101

Why does parseFloat(value) of form text input give NaN?

This returns NaN in the browser alert:

var in1 = parseFloat(document.getElementById('input1').value);
var form = document.getElementById('formC');

form.addEventListener('submit', function() {
    alert(in1);
});

However this works:

var form = document.getElementById('formC');

form.addEventListener('submit', function() {
    var in1 = parseFloat(document.getElementById('input1').value);
    alert(in1);
});

Could someone explain whats going on here? From the error it looks like "in1" is outside the scope of the 'function()' block however doesn't "var" make it global?

The html part:

<form id="formC">
    <input type="text" id="input1">
</form>

Upvotes: 0

Views: 1299

Answers (3)

Scott Marcus
Scott Marcus

Reputation: 65796

Because in the first example, you are attempting to get the value of the input and parse the float out of it immediately (before the user has had a chance to enter any data into it). So, trying to parse a float out of an empty string will yield NaN.

But in the second, you wait until the form is submitted to get the data, which is after the user has entered some data into the input.

On page render the text field is blank.

Yes, and that is when this runs:

var in1 = parseFloat(document.getElementById('input1').value);

and sets the value of in1 to NaN.

But in both cases I manually type a number (5 or 3) into the text field before clicking the submit button.

In the first case, it doesn't matter what you do because the variable in1 already has its value. It's too late, that line has already been executed. You have no code that updates it to use the number you entered.

In the second case, it works because the variable isn't attempting to get the value until you've submitted the form, which is after you entered some data in the input field.

Upvotes: 4

Tanmay_vijay
Tanmay_vijay

Reputation: 619

Sushanth -- and Scott Marcus are correct, you can verify by making following changes in your code

var form = document.getElementById('formC');
var in1 = document.getElementById('input1');

form.addEventListener('submit', function() {
    alert(parseFloat(in1.value));
});

as you can see in1 is accessible inside the function, you just need to read the value once you submit, not before. Above code should not return NaN unless provide invalid float number.

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55750

When the page is rendered I am assuming there is no value in the input. And you already calculated the value of it and just using on submit.

But in the second case you are reading the live value of the input

Upvotes: 2

Related Questions