BMI Calculator using JavaScript with Source code

Explore the world of health and wellness with our BMI Calculator project using JavaScript. In this article, we’ll guide you through the development process and provide you with the source code to create a valuable tool for calculating Body Mass Index, helping users gain insights into their health and fitness.

Index.html

``````
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>BMI Calculator</title>
<body>
<div class="container">
<h1>BMI Calculator</h1>
<form>
<p><label>Height in CM: </label><input type="text" id="height"></p>
<p><label>Weight in KG: </label><input type="text" id="weight"></p>
<button>Calculate</button>
<div id="results"></div>
<div id="weight-guide">
<h3>BMI Weight Guide</h3>
<p>Under Weight = Less than 18.6</p>
<p>Normal Range = 18.6 and 24.9</p>
<p>Overweight = Greater than 24.9</p>
</div>
</form>
</div>
</body>
<script src="script.js"></script>
</html>
``````
``````
.container {
width: 375px;
height: 525px;
margin-left: 350px;
margin-top: 65px;
background-color: yellow;
}
#height, #weight {
width: 150px;
height: 25px;
margin-top: 30px;
}

#weight-guide{
margin-left: 75px;
margin-top: 25px;
}

#results{
font-size: 35px;
margin-left: 90px;
margin-top: 20px;
color: blue;
}

button{
width: 150px;
height: 35px;
margin-left: 90px;
margin-top: 25px;
border-style: none;
background-color: blue;
color: #fff;
font-size: 25px;
}

h1{
}
``````
``````
const form = document.querySelector('form');

e.preventDefault();

const height = parseInt(document.querySelector('#height').value);
const weight = parseInt(document.querySelector('#weight').value);
const results = document.querySelector('#results');

if((height === '') || (height < 0) || (isNaN(height))){
//NaN !== NaN
results.innerHTML = "Please provide a valid height";

} else if (weight === '' || weight < 0 || isNaN(weight)){
results.innerHTML = "Please provide a valid weight";
} else {
//calculate BMI
const bmi = (weight / ((height*height)/10000)).toFixed(2);
//display the results
results.innerHTML = `<span>\${bmi}</span>`
}

});

//notes
//NaN !== NaN, use the isNaN() function
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN

``````