0

I'm fairly new to JS and I think there's a problem with my code in the parts where I'm using Javascript for arithmetic. If someone could show me where I went wrong I'd be very grateful! Currently, everything works except it returns NaN when the calculate button is clicked.

HTML:

<form>
AGE:<br><input id="Age" data-wrapper-class="inputBox" type="text" name="Age"><br>
</form>

<form>
HEIGHT (FEET):<br><input id="Feet" data-wrapper-class="inputBox" type="text" name="Feet"><br>
</form>

<form>
HEIGHT (INCHES):<br><input id="Inches" data-wrapper-class="inputBox" type="text" name="Inches"><br>
</form>

<form>
WEIGHT (POUNDS):<input id="Pounds" data-wrapper-class="inputBox" type="text" name="Pounds"><br>
</form>

<button id="calcButton" class="ui-btn ui-btn-b">Calculate BMR</button>
</div>

<div id="resultsInfo">
<p id="results"></p>
</div>

Javascript / jQuery:

$("#calcButton").click(function() {
var age = document.forms["Age"]; 
var feet = document.forms["Feet"];
var inches = document.forms["Inches"];
var wip = document.forms["Pounds"];
var feetInches = feet * 12;
var heightInches = feetInches + inches;
var weightMen = 6.23 * wip;
var heightMen = 12.7 * heightInches;
var ageMen = 6.8 * age;
var one = 66 + weightMen;
var two = one + heightMen;
var menBMR = two - ageMen;
$("#Calculator").hide();
parseFloat(document.getElementById("results").innerHTML = menBMR);
$("#resultsInfo").show();
});
9
  • 2
    you need to get the elements .value ... and ensure they are a Number Commented Jan 8, 2017 at 22:25
  • 1
    There's no reason to put each <input> element in its own <form>; in fact that's weird. Commented Jan 8, 2017 at 22:25
  • Thanks guys, I'm pretty new to all this, I'll try your suggestions. Commented Jan 8, 2017 at 22:27
  • Change input type = "text" to input type="number" Commented Jan 8, 2017 at 22:37
  • 1
    Rachel, good catch, will do! Commented Jan 8, 2017 at 22:39

1 Answer 1

2

As Jaromanda mentioned, you need to ensure the values are actually a Number value. Once they're a number type then you can do arithmetic operations on them. Here's why this matters:

var str = "12"  // Number value
var num = 12  // String value
console.log(str * 2)  // 1212
console.log(num * 2)  // 24

In your code example, it looks as if you used inputs that are gathering the type="text" which means the values that you get from it would give you a String value. You can convert them to a number using parseInt or parseFloat, or you can change the HTML input type to type="number", I believe.

Sign up to request clarification or add additional context in comments.

1 Comment

Well, they snooze they lose, I guess I'll vote yours best. Thanks for taking the time!

Your Answer

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