Design a BMI Calculator using JavaScript
The Body Mass Index (BMI) Calculator can be used to calculate BMI values based on height and weight. BMI is a fairly reliable indicator of body fatness for most people.
Formula:
BMI = (weight) / (height * height)
// height in cms and weight in kgs
Output Preview:
Image Preview
Approach
BMI is a number calculated from an individual’s weight and height. To find out BMI we will take input from the user (both height and weight) which will be stored in height and weight variables for further calculation. The calculation process is simple, we will simply divide weight in kilograms by the square of the height. Now as per the BMI calculated, it will execute the respective if-else statement. We are also checking if the user is pressing the submit button without entering the inputs, in that case, we are printing provide height or provide weight.
Using HTML we are giving the desired structure, an option for the input, and a submit button. With the help of CSS, we are beautifying our structure by giving colors and desired font, etc.
In the JavaScript section, we are processing the taken input and after calculating, the respective output is printed.
Example: In this example, we will structure in the index.html file and implement the logic in the app.js file
Javascript
window.onload = () => {
let button = document.querySelector( "#btn" );
button.addEventListener( "click" , calculateBMI);
};
function calculateBMI() {
let height = parseInt(document
.querySelector( "#height" ).value);
let weight = parseInt(document
.querySelector( "#weight" ).value);
let result = document.querySelector( "#result" );
if (height === "" || isNaN(height))
result.innerHTML = "Provide a valid Height!" ;
else if (weight === "" || isNaN(weight))
result.innerHTML = "Provide a valid Weight!" ;
else {
let bmi = (weight / ((height * height)
/ 10000)).toFixed(2);
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>`;
}
}
|
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" />
< meta name = "viewport"
content = "width=device-width, initial-scale=1.0" />
< title >BMI Calculator</ title >
</ head >
< body style = "background-color: rgb(244, 255, 244)" >
< div class = "container" >
< h1 >BMI Calculator</ h1 >
< p >Height (in cm)</ p >
< input type = "text" id = "height" />
< p >Weight (in kg)</ p >
< input type = "text" id = "weight" />
< button id = "btn" >Calculate</ button >
< div id = "result" ></ div >
</ div >
</ body >
</ html >
|
Output: Click here to see live code output
Last Updated :
20 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...