How to Make a BMI Calculator in Javascript?

In this blog post, we make a BMI calculator in simple javascript code. BMI (Body mass index) formula measures total body fat and whether a person is a healthy weight.

First, make an HTML form to get input value from the user.

HTML

<!DOCTYPE html>
<html>

<head>
	<title>BMI Calculator in Javascript</title>
</head>

<body>
	<div class="container">
		<h3>BMI Calculator in Javascript</h3>
    
    <label for="height">Height (in cm)</label>
		<input type="text" id="height"> <br>

    <label for="weight">Weight (in kg)</label>
		<input type="text" id="weight"> <br>
  <hr>
    <button onclick="calculateBMI()">Calculate</button>

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

</html>

javascript

function calculateBMI() {
  
    let height = parseInt(document.querySelector("#height").value);
    let weight = parseInt(document.querySelector("#weight").value);

    let result = document.querySelector("#result");

   
    // validation value or not
    if (height === "" || isNaN(height))
        result.innerHTML = "Enter a valid Height!";

    else if (weight === "" || isNaN(weight))
        result.innerHTML = "Enter a valid Weight!";

    // If entered value is valid, calculate the BMI
    else {
      
        let bmi = (weight / ((height * height) / 10000)).toFixed(2);

        // Dividing as per the bmi conditions
        if (bmi < 18.6) result.innerHTML =
            `Under Weight : <span>${bmi}</span>`;

        else if (bmi >= 18.6 && bmi < 24.9)
            result.innerHTML =
            `Normal : <span>${bmi}</span>`;

        else result.innerHTML =
            `Over Weight : <span>${bmi}</span>`;
    }
}

First of all, we have got the input value and calculated it by keeping the value in the BMI formula. Before that, we validated the entered value.

The calculated value or result is printed in HTML through innerHTML.

Hope this code will be helpful for you.