This is rather simple stuff yet I see it so rarely used. In any dating sites, health calculators, DIY stuff calculators etc they ask you to enter weight and height of something (or your own weight and height) only in their preferred measurement system (metric or Imperial). Boring! This simple javascript will convert the units and instantly fill the appropriate fields in the form.
To get a better idea how it works see it in this calculator:
http://calendarscripts.info/weight-loss-calculator.html
These are two javascript functions that should of course be properly called on "onkeyup" event in the appropriate fields.
Note that the field names from the form are hardcoded in the functions here but obviously you could come with more abstracted solution.
// 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;
}
}