Creating a Body Mass Index (BMI) calculator in JavaScript involves taking the user's height and weight as inputs, calculating the BMI using the formula, and then displaying the result along with a category (e.g., underweight, normal weight, overweight, etc.).
JavaScript (script.js
)
function calculateBMI() {
// Get the input values
const weight = document.getElementById('weight').value;
const height = document.getElementById('height').value;
// Validate inputs
if (weight === "" || height === "") {
alert("Please enter both weight and height.");
return;
}
// Convert height from cm to meters
const heightInMeters = height / 100;
// Calculate BMI
const bmi = weight / (heightInMeters * heightInMeters);
// Determine BMI category
let category = "";
if (bmi < 18.5) {
category = "Underweight";
} else if (bmi >= 18.5 && bmi < 24.9) {
category = "Normal weight";
} else if (bmi >= 25 && bmi < 29.9) {
category = "Overweight";
} else {
category = "Obese";
}
// Display the result
document.getElementById('bmiResult').textContent =
"Your BMI is " + bmi.toFixed(2) + " (" + category + ")";
}
Explanation:
-
HTML Structure:
- A simple form with two input fields (
weight
and height
) and a button to calculate BMI.
- A
div
with the class result
where the BMI and its category will be displayed.
-
CSS Styling:
- Basic styling to make the form look neat and centered.
- The button changes color when hovered to improve user interaction.
-
JavaScript Functionality:
- The
calculateBMI
function is triggered when the user clicks the "Calculate BMI" button.
- It retrieves the user's weight and height from the input fields.
- The height is converted from centimeters to meters.
- The BMI is calculated using the formula:BMI=height (m)2weight (kg)
- Based on the BMI value, a category is assigned (Underweight, Normal weight, Overweight, or Obese).
- The BMI value (rounded to two decimal places) and the category are displayed on the page.
This example can be expanded with additional features, such as input validation to ensure only numbers are entered, or providing more detailed health advice based on the BMI category.