I'm trying to create a BMI Calculator on JavaScript. I'm facing a problem with the calculation itself. It always returns 'NaN'. I tried to use parseInt(), parseFloat(), Number(), it didn't work. I know my problem is in my 'imc' variable because when I put numbers instead of 'height' and 'weight', it doesn't returns 'NaN' anymore, but I don't know what exactly is the problem. Also, I don't have any error in the console. Can anyone help me please?
Here is my code:
HTML:
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Calculateur d'IMC</title>
<link rel="stylesheet" href="imc.css">
<script src="imc.js"></script>
</head>
<body>
<h1>Calculateur d'IMC</h1>
<h2>Bienvenue! Entrez vos informations ci-dessous pour calculer votre IMC.</h2>
<div id="calcul">
<h3>Poids:</h3>
<input type="number" id="weightInput" placeholder="Votre poids..."></input>
<h3>Taille:</h3>
<input type="number" id="heightInput" placeholder="Votre taille..."></input><br/>
</div>
<button onclick="calculate()" id="button1">Calculez!</button>
<div id="result"></div>
</body>
<script src="imc.js"></script>
</html>
JS:
var height = document.querySelector('#heightInput'.value);
var element = document.querySelector('button');
function calculate() {
let imc = (weight / (height) **2);
console.log(imc);
alert('Vous avez un IMC de ' imc '!');
return imc;
}
Thanks!
CodePudding user response:
I didn't manage to figure out why it prints out NaN but i fixed it and it seems to work fine
var element = document.querySelector('button');
function calculate() {
var height = new Number(document.getElementById("heightInput").value);
var weight = new Number(document.getElementById("weightInput").value);
let imc = (weight / (height) **2);
console.log(imc);
alert('Vous avez un IMC de ' imc '!');
return imc;
}
CodePudding user response:
It seems that the core problem is the order of execution. Your script loaded first and then executed immediately. During its execution it tried to get access to some DOM elements before DOM was ready to operate with. Try to logging variable values in your script and you see.
CodePudding user response:
var element = document.querySelector('button');
function calculate() {
var height = new Number(document.getElementById("heightInput").value);
var weight = new Number(document.getElementById("weightInput").value);
let imc = (weight / (height) **2);
console.log(imc);
alert('Vous avez un IMC de ' imc '!');
return imc;
}