Java Script Body Mass Index Calculator
By Stephen Bucaro
To determine if you are overweight physicians use your body mass index (BMI).
BMI is a formula that was developed in 1869 by the Belgian mathematician
Adolphe Quetelet. BMI is calculated by dividing your weight in kilograms
by your height in meters squared.
BMI = Weight [in kilograms] / (Height [in meters])²
BMI is only valid
for people over the age of 20, the government has developed special charts for younger people.
If you have a Web site related to health or dieting, or you just want to provide
more useful features on your Web site, you can provide a BMI calculator. The user
enters their height and weight into the calculator and receives their BMI as a result.
In this article I'll show you how to code a Java Script BMI calculator for your Web site.
I will explain everything in detail, so even if you have no programming experience you
can easily do this. Or you can just cut and paste the code into your webpage.
The first thing you need is a form for the user to enter their height and weight. The
code for the form is shown below.
<form>
Height: <input type="text" name="height">
Weight: <input type="text" name="weight">
<input type="button" value="Calculate BMI"
onClick="calcBMI(this.form.height.value,
this.form.weight.value)">
<form>
Note that the form defines a button with the label "Calculate BMI". The onClick
event of the button passes the contents of the two text boxes to a function named
calcBMI. The code for the calcBMI function is shown below.
<script language="JavaScript">
function calcBMI(height, weight)
{
var M = height * .0254;
var KG = weight * .4536;
var BMI = KG/(M*M);
alert(BMI);
}
</script>
Note that the calcBMI function is contained within a Java Script code block.
This code block can be placed anywhere in your webpage, but typically it would go in
the head section. To use the BMI calculator, the user enters their height in inches
and their weight in pounds. The calcBMI function converts inches to meters
and pounds to kilograms, then calculates the BMI and displays it in a popup box.
What if the use accidentally enters a character instead of a digit? For example they
might enter an o rather than an 0. In the revised function shown below I have added
an if/else structure that uses the Java Script built-in isNaN function to check
for non-numeric characters. The isNaN function returns true if the value passed
to it is not a number. In that case the user with get a popup box with the message "Error".
function calcBMI(height, weight)
{
if(isNaN(height) || isNaN(weight))
{
alert("Error");
}
else
{
var M = height * .0254;
var KG = weight * .4536;
var BMI = Math.round(KG/(M*M));
alert(BMI);
}
}
Note the use of the Java Script built-in Math.round function near the bottom of the
code. The Math.round function removes digits to the right of the decimal point.
|