Jacked_Nerd
Jacked_Nerd

Reputation: 237

Javascript NaN bug

Here is my js function. When I enter the data i get NaN

//BMI is defined as BMI = ( Weight in Pounds / ( Height in inches x Height in inches ) ) x 703
function calculatebmi(weight, height){
    //window.alert("hello");
    var weight = parseInt(document.getElementsByName("weight_pounds"));
    var height = parseInt(document.getElementsByName("height_inches"));

    var bmi = parseInt(((weight/height)*703));
    window.alert("your BMI is: " + bmi);
}

I have tried math.floor and innerHTML. Both didn't help.

The input tag type is number, in case anyone was wondering.

Upvotes: 1

Views: 470

Answers (3)

isvforall
isvforall

Reputation: 8926

document.getElementsByName returns NodeList

You need to use [0] notation to get first element from this collection and then use value property.

var value = document.getElementsByName('weight_pounds')[0].value;
var weight = parseInt(value, 10);

For parseInt function radix(second parameter) by default is 10, but you need to specify it. From MDN:

Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior.

Upvotes: 4

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try to pass the value inside of parseInt instead of a node object,

 var weight = parseInt(document.getElementsByName("weight_pounds")[0].value);

If you pass an object into parseInt rather than a numeric string, it will return NaN. Also it is advised to use the radix parameter of parseInt as 10, but nowadays recent browser will consider radix as 10 by default.

Note that, getElementsByName will return a html collection, so you cannot access the value of required element directly. You have to get its first element by using bracket notation [0] and access its value. So to avoid such problems you can use .querySelector() like below,

 var weight = parseInt(document.querySelector("input[name='weight_pounds'])").value);

Upvotes: 2

elixenide
elixenide

Reputation: 44833

You're trying to parse the nodes themselves, when you should be trying to parse their values (with .value), and you don't index the collection returned by getElementsByName:

var weight = parseInt(document.getElementsByName("weight_pounds")[0].value);
var height = parseInt(document.getElementsByName("height_inches")[0].value);

Upvotes: 0

Related Questions