×

Design a BMI calculator using JavaScript

BMI calculator

BMI stands for Body Mass Indicator. It is a numeric value which is calculated based on the height and weight of a person. It represents the fatness of the body by a numeric value. The formula of BMI is: BMI = kg/m2

Let’s suppose for a person if weight is W (in kg) and his height is H (in meter) then his BMI will be:

BMI= (W) / (H*H)

For creating the BMI calculator, we will use HTML, CSS, and JavaScript. We will ask the user to enter his weight in the centimeter and also we will ask the user to enter his weight in kilograms. If any input is empty then we will not calculate the BMI and there will be a warning stating that empty fields are not allowed.

After entering the values, the user will click the button and his BMI will be displayed on the screen and based on the values of the BMI we can display the message if it is under fat or overfat using simple if else conditions.

HTML code-

<!DOCTYPE html>
<html>


<head>


      // we are adding the JavaScript file into html code
	<script src="script.js"></script>
      <style>
		body{
		  font-family: verdana;
		  font-weight:800;
		}
		input{
		  text-decoration:none;
		  outline :none;
		  border-bottom: 2px solid grey;
		}
	
	</style>


</head>


<body>
	<div class="main_div">
		<h1> Welcome to JavatPoints BMI Calculator</h1>


		<h2>Enter the Height (in cm)</h2>


		<input type="text" id="height">


		<h2>Enter the Weight (in kg)</h2>


		<input type="text" id="weight">


		<button id="btn">Calculate Your BMI </button>
            
          // here div section is empty as BMI will be placed here dynamic
		<div id="result"></div>
	</div>
</body>


</html>

JavaScript Code-

window.onload = () => {
	let bmiButton = document.querySelector("#btn");


	bmiButton .addEventListener("click", getBMI);
};


function getBMI() {


	let H = parseInt(document
			.querySelector("#height").value);


	
	let W= parseInt(document
			.querySelector("#weight").value);


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




	if (H=== "" || isNaN(H))
		ans.innerHTML = "Provide a valid Height!";


	else if (W=== "" || isNaN(W))
		ans.innerHTML = "Provide a valid Weight!";


	else {


		// Fixing upto 2 decimal places
		let bmi = (W / ((H * H)/ 10000)).toFixed(2);
							


		if (bmi < 18.6) ans.innerHTML =
			`You are Underweight : <span>${bmi}</span>`;


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


		else ans.innerHTML =
			` You are Overweight : <span>${bmi}</span>`;
	}
}

Code Explanation-

We have here two files: the first one id idnex.js and the second one script.js. Although we can use the third file of CSS but currently we are ignoring that CSS because we are more focused on the functionality of this calculator instead of styling.

In the index.js file first, we have included the script.js file so that all the functionality which is written in the JavaScript file is merged to particular elements of HTML.

Now in the body section of the HTML file, we have two input boxes of type text where the user will enter its height and weight. Then, we have a button and we have given a unique id to this button.

We have another div section which will be empty initially and when we calculate the BMI then it will be updated according to that value.

Now, let’s talk about the JavaScript file where we have implemented all the functionality of our calculator.

As the window is loaded on the screen, we will add the event listener with the click of the button and attach a function to calculate the BMI. Now let's see the function’s description.

Initially, we will take the value from the input box and store it in the variables. The value of height will be stored in the variable ‘H’ and the value of weight will be stored in the variable ‘W’.

Now if H is null then in the result div we will print the text to enter a valid height. Now if W is empty then we will print the text in the div result to enter the valid weight.

If users enter both values correctly then we will calculate the BMI using the formula and we will have if else conditions.

  • If the BMI value is lesser than 18.6, we will print as underweight.
  • If the value is greater than 18.6 but less than 24.9, we will just print the text as normal weight.
  • Else BMI value represents the overweight so; we will print the corresponding text.

Output:

Design a BMI calculator using JavaScript

Related Topics

Javascript Forms Validation

Form validation works at server, after client had entered all the necessary details and then pressed submit button. JavaScript provides the facility to validate the form on the client side...

9 minutes read.

Javascript Dialog Box

A JavaScript dialog box is predefined function which is used to perform different task. Some functions are used in JavaScript Dialog box. FunctionDescriptionalert()To give alert message to userprompt()To input value from...

2 minutes read.

Functional Programming in JavaScript

Most developers work with object-oriented programming while developing their applications, but sometimes they need to change their approach to solve some specific tasks. Although mostly we tend to go for...

6 minutes read.

Javascript comment

Introduction In programming languages, comments are a method to include meaningful annotations within the code that the compiler or interpreter will ignore at run time. That is to say, though comments...

7 minutes read.

Javascript Password Validation

Here we see that how to validate any password field. Like password field can be blank and length of password is minimum 8 characters. Example <!DOCTYPE html>   <html>   <head>   <script>   functionpass_validation()   {     var password=document.myform.password.value;     if (password==null || password=="")   {     alert("password can't be blank");     return false;     }   else if(password.length<8)   {     alert("Password must be at least 8 characters long.");     return false;       }     }     </script>   </head>   <body>   <form name="myform" method="post" action="register.php" onsubmit="return pass_validation()" >   Password: <input type="password" name="password">   <input type="submit" value="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

JavaScript Image resize before upload

Image resizing can be a quite tedious task, so it is usually done on the server-side. The resized image file is then delivered to the client side. However, sometimes the...

3 minutes read.

Javascript Print

JavaScript help's the functionality using the print function of window object. In JavaScript print function window.print() print the current web page when it executed. We can call function directly using onclick...

1 minute read.

Javascript Object

An object is an entity having state and behavior. JavaScript is an object oriented scripting language. JavaScript is template based not class based but we can create object directly. Syntax to...

2 minutes read.

Synchronous and Asynchronous in JavaScript

JavaScript is a powerful and versatile language that is used all over the web, from small websites to large applications. It is essential for developers to understand the differences between...

9 minutes read.

Javascript Math

Math is build-in object that has properties and methods for mathematical constants and functions. It allows you to perform mathematical tasks on numbers. Syntax varpi_val = Math.PI; varsin_val = Math.sin(30); Examples Math.pow() Math.pow(x,y) returns the value of x to the power...

2 minutes read.

Minify JavaScript

What do you mean by the term ‘Minification’? The technique of minification reduces the amount of code and markup in your websites and scripting files. It's one of the most used...

4 minutes read.

Javascript Document Object

Document object represents the whole HTML documents. When HTML document is loaded in browser it becomes the document object. It is the root elements that represent the HTML documents. With the help of...

2 minutes read.

Javascript Operators

The concept of operators is the basis of nearly all programming languages used in today's computing systems. Operators facilitate the execution of certain functions. For instance, the (+) symbol is...

8 minutes read.

JavaScript Time Picker Demo

Time Pickers in JavaScript are lightweight and mobile-friendly controls that let the users enter or select date and time values. These values can be from a pop-up calendar or a...

5 minutes read.

Javascript String

String object works with series of characters. It is used to store and manipulate text. There are two ways to create string in JavaScript: String literal. Using new keyword. String literal By using double quotes...

4 minutes read.

Javascript Cookies

Cookie is a piece of data which is sent from a website and stored locally by the user's browser. Cookie is needed because HTTP is stateless protocol. Today most of...

1 minute read.

JavaScript Console log Multiple variables

What does console.log() do in JavaScript? The console.log() is a function in JavaScript language. It is used to: Print any message in the console which is visible to the userPrint the values...

3 minutes read.

JavaScript focus on input

In JavaScript, the elements can be focused using either focus() method or onfocus() event. What is focus() method? When we want to focus on an element (if it can be focused) or...

4 minutes read.

Javascript Page Redirect

The window.location object can be used to get the current page address (URL) and to redirect browser to new page. In some websites when we visit, we face a situation where we...

3 minutes read.

Javascript Number

The Number object is a wrapper object which allows you to work with numerical values. The number object is created using the Number() constructor.It may be integer or floating-point. Syntax var n=new Number(value); Examples <!DOCTYPE html>   <html>   <body>   <script>   var x=100;//integer value   var y=100.7;//floating point value   var z=12e5;//exponent value, output: 1200000   var n=new Number(20);//integer value by number object     document.write(x+" "+y+" "+z+" "+n);   </script>   </body>   </html> Try Now Output 100 100.7 1200000 20 Description The primary...

1 minute read.