我正在构建一个非常简单的BMI计算器但是提交的实例我可以找到总值输入并实时显示消息(div)而无需提交?
<label>Weight in kg
<input text="text" name="weight" id="input1">
</label>
<BR>
<label>Height in cm
<input text="text" name="height" id="input2">
</label>
<BR>
<button type="button" id="button1">Calculate</button>
document.getElementById('button1').onclick = function(yourBmi) {
var weight = document.getElementById('input1').value;
var height = document.getElementById('input2').value;
height = height / 100
var bmi = ((weight) / (height * height));
var result = ""
if (bmi < 18.5) {
result= "Underweight";
} else if (bmi > 25 && bmi < 30) {
result= "Overweight";
} else if (bmi > 30) {
result = "Obese";
} else {
result = "Normal";
}
bmi = bmi.toFixed(2);
alert("Your weight is " + weight + "kg" + "\nYour height is " + height + "m" + "\nyour BMI is " + bmi + "\nTherefore you are " + result);
};
答案 0 :(得分:1)
要实现这一目标,您可以将逻辑提取到函数中,并在单击按钮时调用它,以及在其中一个输入上发生keyup
事件时。
您还应该添加一些(至少是基本的)验证来检查BMI值是否有效。
我希望警报替换为一条消息,具体取决于值,因此就像div show隐藏
一样
在这种情况下,您可以在加载时添加隐藏的div
,您可以根据需要更新文本并显示,如下所示:
function calculateBMI() {
var weight = document.getElementById('input1').value;
var height = document.getElementById('input2').value / 100;
var output = document.getElementById('output');
var bmi = weight / (height * height);
var result = "";
if (bmi < 18.5) {
result = "Underweight";
} else if (bmi > 25 && bmi <= 30) {
result = "Overweight";
} else if (bmi > 30) {
result = "Obese";
} else {
result = "Normal";
}
bmi = bmi.toFixed(2);
if (bmi && bmi != Number.POSITIVE_INFINITY && !isNaN(bmi)) {
output.innerHTML = 'Your weight is ' + weight + 'kg<br />Your height is ' + height + 'm<br />your BMI is ' + bmi + '<br />Therefore you are ' + result;
output.style.display = 'block';
} else {
result.innerHTML = '';
output.style.display = 'none';
}
}
document.getElementById('input1').addEventListener('keyup', calculateBMI);
document.getElementById('input2').addEventListener('keyup', calculateBMI);
document.getElementById('button1').addEventListener('click', calculateBMI);
&#13;
#output { display: none; }
&#13;
<label>Weight in kg
<input text="text" name="weight" id="input1">
</label><br />
<label>Height in cm
<input text="text" name="height" id="input2">
</label><br />
<button type="button" id="button1">Calculate</button>
<div id="output"></div>
&#13;