Convert Height and Weight

Submitted by:Jhon Smith

Date added:11 November, 2013

Category:JavaScript

These are two JavaScript functions that should of course be properly called on "onkeyup" event in the appropriate fields.

Tags: convert height , convert weight

Code Snippet:

// converts height
// fld variable is the field object sent as "this"
// example call: <input type="text" onkeyup="calculateHeight(this)">
function calculateHeight(fld)
{
// finding whether this is one of the imperial unit fields
if(fld.name=="height_in" || fld.name=="height_ft")
{
// convert to height in inches
if(isNaN(fld.form.height_in.value) || fld.form.height_in.value=="") inches=0;
else inches=fld.form.height_in.value;

if(isNaN(fld.form.height_ft.value) || fld.form.height_ft.value=="") feet=0;
else feet=fld.form.height_ft.value;

inches=parseInt(parseInt(feet*12) + parseInt(inches));

var h=Math.round(inches*2.54); // now we have it in cm

fld.form.height_cm.value=h; // and now we populate the cm field
}
else
{
// turn cm into feets and inches
if(isNaN(fld.value) || fld.value=="") cm=0;
else cm=fld.value;

totalInches=Math.round(cm/2.54);
inches=totalInches%12;
feet=(totalInches-inches)/12;

// populate the fields
fld.form.height_ft.value=feet;
fld.form.height_in.value=inches;
}
}

// converts weight
// fld variable is the field object sent as "this"
// example call: <input type="text" onkeyup="calculateWeight(this);">
function calculateWeight(fld)
{
if(fld.name=="weight_lb" || fld.name=="lose_lb")
{
// calculate in kg
if(isNaN(fld.value) || fld.value=="") w=0;
else w=fld.value;

var wKg=Math.round(w*0.453*10)/10;

if(fld.name=="weight_lb") fld.form.weight_kg.value=wKg;
else fld.form.lose_kg.value=wKg;
}
else
{
// calculate in lbs
if(isNaN(fld.value) || fld.value=="") w=0;
else w=fld.value;

var wP=Math.round(w*2.2);

if(fld.name=='weight_kg') fld.form.weight_lb.value=wP;
else fld.form.lose_lb.value=wP;
}
}
 
 

Comments