I’m trying to create a BMI calculator that displays a user’s BMI once they submit their height and weight. But the results won’t display in the p tag.
Here’s the code:
HTML
<form>
<label for="height">Please input your height:</label>
<input id="height" type="text" name="" value="" placeholder="height">
<label for="weight">Please input your weight:</label>
<input id="weight" type="text" name="" value="" placeholder="weight">
<button onclick="BMIcalc()" type="button" name="button">Submit</button>
</form>
<h3>Your BMI is: </h3>
<p class="result"></p>
Then for Javascript:
let myHeight = document.getElementById("height");
let myWeight = document.getElementById("weight");
let answer = document.getElementsByClassName("result");
function BMIcalc() {
if (myHeight.value === "" || myWeight.value === "") {
alert("Please fill in your height and weight!");
} else{
const BMI = myWeight.value / myHeight.value**2;
answer.value = BMI;
}
}
The answer won’t display in the p tag
However, if I use console.log(), the result is displayed meaning the function is working correctly. But I need to be able to show the result to the user.
I’ve also tried using:
let myHeight = document.getElementById("height");
let myWeight = document.getElementById("weight");
function BMIcalc() {
if (myHeight.value === "" || myWeight.value === "") {
alert("Please fill in your height and weight!");
} else{
const BMI = myWeight.value / myHeight.value**2;
const answer = BMI;
document.getElementsByClassName("result").innerText = answer;
}
}
Nothing works
2
Answers
I think you need to change from:
to:
And later in your HTML change to:
But, if you really need class in your p tag, use in your JS:
See the docs about querySelector.
You need some refactoring in your code: