BMI Calculator

by arp51

HTML

<div id="weightWrap">
    <label for="weight">How much do you weigh?</label>
    <br />
    <input type="text" id="weight" name="weight" />
    <input type="radio" name="weightUnit" checked="true" value="kg">kg</input>
    <input type="radio" name="weightUnit" value="lbs">lbs</input>
</div>
<div id="heightWrap">
    <label for="height">How tall are you?</label>
    <br/>
    <input type="text" id="height" name="height" />
    <input type="radio" name="heightUnit" checked="true" value="m">m</input>
    <input type="radio" name="heightUnit" value="in">in</input>
</div>
<a href="#" id="calculate">Calculate</a>

<div id="result"></div>

CSS

body {
    padding:10px;
    background:#eee;
}
input {
    padding:5px;
    border:none;
}
#result {
    margin:20px 0px;
    padding:10px;
}

JavaScript

/ Convert Inches to Centimeters
function convertHeight(inches) {
    return inches * 0.0254;
}

/ / Convert Pounds to Kilograms

function convertWeight(pounds) {
    return pounds / 2.20462262185;
}

// Find Unit of Measurement
function findUnit(unit) {
    var output;
    for (i = 0; i < unit.length; i++) {
        if (unit[i].checked === true) {
            output = unit[i].value;
        }
    }
    return output;
}

// Cache Event Elements
var calculate = $('#calculate');
var result = $('#result');

// RENDER SELECTED UNIT
calculate.on('click', function () {
    var weight = document.getElementById('weight').value;
    var height = document.getElementById('height').value;
    var weightUnit = findUnit(document.getElementsByName('weightUnit'));
    var heightUnit = findUnit(document.getElementsByName('heightUnit'));
    var w;
    //console.log('Weight is measured in: ' + weightUnit + '\nHeight is measured in: ' + heightUnit);

    // If measurement is in pounds, do the math.
    if (weightUnit == 'lbs') {
        w = convertWeight(weight);
        console.log(w + "kg");
    } else {
        w = weight;
        console.log(w + "kg");
    }

    // If height measurement is in inches, do the math.
    if (heightUnit == 'in') {
        h = convertHeight(height);
        console.log(h + "m");
    } else {
        h = height;
        console.log(h + "m");
    };

    result.text('Your BMI is: ' + w / (h * h));
});