Ian Ian - 2 months ago 31
HTML Question

Javascript BMI Calculator

Having trouble getting this to print anything in JSFiddle, although everything looks right to me. I'm unsure as to why HTML is not displaying the answer, but any help is welcome. Thanks!

HTML:

<h2>BMI Calculator</h2>
<p>
Enter your weight in pounds:
<input type="text" id="weight">
</p>

<p>
Enter your height in inches:
<input type="text" id="height">
</p>

<input type="button" onclick="bmiCalculator()" value="calculate">
<p id="output"></p>


Javascript:

function bmiCalculator() {
var weight = Number(document.getElementById("weight").value);
var height = Number(document.getElementById("height").value);
var finalWeight = weight * .45;
var finalHeight = height * .025;

var BMI = (finalWeight / Math.pow(finalHeight, 2));

document.getElementById("output").innerHTML = BMI;
}

Answer

There is a syntax error in your code (you're missing a closing parenthesis in your BMI expression). Here's the fixed code (I just added ) right where it was needed) and it seems to me to be working fine.

function bmiCalculator() {

  var weight = Number(document.getElementById("weight").value);
  var height = Number(document.getElementById("height").value);
  var finalWeight = weight * .45;
  var finalHeight = height * .025;


var BMI = (finalWeight / Math.pow(finalHeight, 2));

document.getElementById("output").innerHTML = BMI;

}
<h2>
 BMI Calculator
</h2>

<p>
  Enter your weight in pounds:
  <input type="text" id="weight">
</p>

<p>
  Enter your height in inches:
   <input type="text" id="height">
</p>

<input type="button" onclick="bmiCalculator()" value="calculate">
  <p id="output" ></p>

Note: this code will not work on jsfiddle.net unless the Javascript option Load Type is set to No wrap - in <body>

I found that out thanks to this other stack: Onclick event not firing on jsfiddle.net

Comments