Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

BMI Calculator JavaScript

I’m very new to JavaScript, but I try to challenge myself a bit with some small projects.
Whenever I get stuck, I Google the problem and try to solve it that way, but this time I can’t figure out why my code isn’t working.

function berekenBMI() {
  var gewicht = Number(document.getElementById("gewicht"); // weight
  var lengte = Number(document.getElementById("lengte"); // height
  var BMI = gewicht / Math.pow(lengte, 2); // the calculation 

  document.getElementById("output").innerHTML = Math.round(BMI * 100) / 100;

  if (BMI < 18.5) document.getElementById("comment").innerHTML = '5';
  if (BMI >= 18.5 && BMI < 25) document.getElementById("comment").innerHTML = '2';
  if (BMI >= 25 && BMI <= 30) document.getElementById("comment").innerHTML = 'geen';
  if (BMI > 30) document.getElementById("comment").innerHTML = 'nooit geen';
}
<h2> BMI Berekenen </h2>

<div class="container">

  <label>Gewicht (KG): </label>
  <input type="text" id="gewicht">

  <label>Lengte (Meters): </label>
  <input type="text" id="lengte">

  <input type="submit" value="Bereken mijn BMI" onclick="berekenBMI()">

</div>

<h3>
  Jouw BMI is: <span id="output"> ? </span>
</h3>

<h4>
  Je mag <span id="comment"> zoveel </span> koekjes!
</h4>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There are 2 problems here. The first one is rather simple, you’re just missing closing parentheses when assigning the gewicht and lengte variables to close out the Number function.

The second issue is a little less obvious to the untrained eye. In your JavaScript, you’re calling document.getElementById() twice, and trying to convert the output to a Number both times. The output of document.getElementById is an Element object. It’s trying to convert the object itself to a number, which returns NaN (Not a Number). To fix this, add .value after each document.getElementById() that you need to get a string value from. The value property contains the string value of the text box. This is true for almost every element that takes input.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading