🔒 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
  • 419
    Views
  • 1
    Participants
Last reply from:
Unknown user

Trending Topics

Online now

Members online
966
Guests online
1,449
Total visitors
2,415

Forum statistics

Threads
2,273,369
Posts
28,949,029
Members
1,235,719
Latest member
Wzpprince
Back
Top