Posts Tagged ‘Javascript’

Javascript Body Mass Index Script

// February 13th, 2009 // No Comments » // Development, Javascript

I was recently playing with some JavaScript which calculates your BMI or body mass index. It is just a small bit of code and I didn’t want to use any frameworks. Obviously I want to use the DOM and have no intrusive code.

There are two calculations to BMI. One is using the metric system the other using the imperial system.

For the imperial system the formula is:

1
(weight-in-pounds  *  703) / (height-in-inches * height-in-inches)

For the metric system the formula is:

1
(weight-in-kilos) / (height-in-meters * height-in-meters)

Getting the values of the form select box and text boxes is done using document.getElementById. As these are text values I used parseInt() in order to do arithmetic with the values.

Once the totals were found I wanted to round the values to 2 decimal places using Math.round(bmi*100)/100;

Instead of an alert box to give the results I created an empty div as I wanted to set the content of it dynamically. I gave an id to the div of “results”. I first create a reference to the DOM node. Once you have this you can remove any of the child nodes using node.removeChild(node.childNodes[0]). If you don’t do this, each time the script is called the message will be appended to the last one. Now there are no children, you can add one using document.getElementById(“results”).appendChild(textnode).

1
2
3
4
var node = document.getElementById("results");
node.removeChild(node.childNodes[0]);
var textnode = document.createTextNode(result);
document.getElementById("results").appendChild(textnode);

Here is the code in full:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function get_bmi()
{
	var bmi = 0;
	var system = document.getElementById("system").value;
 
	if(system == "standard")
	{
		var inches = parseInt(document.getElementById("inches").value);
		inches += parseInt(document.getElementById("feet").value) * 12;
		bmi = (document.getElementById("pounds").value * 703) / (inches * inches);
	}
	else if (system == "metric")
	{	
		var meters = document.getElementById("centimeters").value / 100;	
		bmi = document.getElementById("kilos").value / (meters * meters);
	}
	bmi = Math.round(bmi*100)/100;
	result = "Your BMI is " + bmi;
	var node = document.getElementById("results");
	node.removeChild(node.childNodes[0]);
	var textnode = document.createTextNode(result);
	document.getElementById("results").appendChild(textnode);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
function show_hide()
{
	if(document.getElementById("system").value =="standard")
	{
		document.getElementById("standard_div").style.display = "block";
		document.getElementById("metric_div").style.display = "none";
	}
	else
	{
		document.getElementById("standard_div").style.display = "none";
		document.getElementById("metric_div").style.display = "block";
	}
}

Here is the working script: