🔒 Closed How to code a BMI using javascript? (bot)

Status
Not open for further replies.
To code a BMI calculator using JavaScript, you can follow these steps:

1. Create a function that takes the weight and height as parameters.
2. Calculate the BMI using the formula: BMI = weight(kg) / (height(m) * height(m)).
3. Round the BMI to two decimal places using the toFixed() method.
4. Display the result in the console or on the webpage.

Here's an example code snippet:

Code:
function calculateBMI(weight, height) {
  var bmi = weight / (height * height);
  return bmi.toFixed(2);
}

var weight = 70; // in kg
var height = 1.75; // in meters
var bmi = calculateBMI(weight, height);

console.log("Your BMI is " + bmi);

You can also create an HTML form to take input from the user and display the result on the webpage:

Code:
<form>
  <label for="weight">Weight (in kg):</label>
  <input type="number" id="weight" name="weight"><br>

  <label for="height">Height (in meters):</label>
  <input type="number" id="height" name="height"><br>

  <button type="button" onclick="calculate()">Calculate BMI</button>
</form>

<p id="result"></p>

<script>
  function calculate() {
    var weight = document.getElementById("weight").value;
    var height = document.getElementById("height").value;

    var bmi = weight / (height * height);
    document.getElementById("result").innerHTML = "Your BMI is " + bmi.toFixed(2);
  }
</script>

This code creates an HTML form with input fields for weight and height, and a button to calculate the BMI. When the button is clicked, the calculate() function is called, which gets the values of weight and height from the input fields, calculates the BMI, and displays the result on the webpage.
 
Status
Not open for further replies.

About this Thread

  • 1
    Replies
  • 459
    Views
  • 1
    Participants
Last reply from:
Unknown user

Online now

Members online
1,061
Guests online
11,721
Total visitors
12,782

Forum statistics

Threads
2,334,805
Posts
29,279,704
Members
1,135,677
Latest member
efkaaa
Back
Top