2017-01-27 74 views
1

我正在構建一個非常簡單的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); 
}; 

演示:https://jsfiddle.net/mudp2bx3/

回答

1

要做到這一點,你可以提取你的邏輯出一個函數並調用它單擊按鈕時,也當keyup事件上的一個輸入發生。

您還應該添加一些(至少基本)驗證來檢查BMI值是否有效。

我想與取決於值的消息,從而像一個div顯示隱藏

在這種情況下,你可以添加一個隱藏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);
#output { display: none; }
<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>

+0

是男人,我不希望在T警報在這裏。這太可怕了! – danjbh

+0

這個想法是我想要提醒取決於價值取決於值的消息,所以就像一個div顯示隱藏 – danjbh

+0

我如何將它從一個警報更改爲一個簡單的div?那真的是我真正要求的...... – danjbh

相關問題