Javascript 体重指数计算程序

Javascript 体重指数计算程序,javascript,html,dom,Javascript,Html,Dom,我已经创建了一个应用程序来计算体重指数。基本上,以下是我希望该应用程序的工作方式,并写了如下内容: 你只需以英寸为单位输入身高,以磅为单位输入体重 该应用程序将计算你的BMI,然后告诉你是体重不足、正常、肥胖还是超重 如果您为身高或体重输入非正值,程序将显示一条错误消息“输入无效。请输入正数”,并将突出显示需要修复/输入有效值的框 我遇到了两个问题。 我可以让程序显示BMI结果,但目前我不知道如何编写程序来显示用户是体重不足、正常、肥胖还是超重。 如果BMI=18.5,25和30,则超重

我已经创建了一个应用程序来计算体重指数。基本上,以下是我希望该应用程序的工作方式,并写了如下内容:

  • 你只需以英寸为单位输入身高,以磅为单位输入体重

  • 该应用程序将计算你的BMI,然后告诉你是体重不足、正常、肥胖还是超重

  • 如果您为身高或体重输入非正值,程序将显示一条错误消息“输入无效。请输入正数”,并将突出显示需要修复/输入有效值的框

我遇到了两个问题。

  • 我可以让程序显示BMI结果,但目前我不知道如何编写程序来显示用户是体重不足、正常、肥胖还是超重。 如果BMI<18.5,则体重不足,BMI>=18.5,25和30,则超重

  • 我想在“计算体重指数”按钮下方显示错误(告诉用户输入正值,而不是缺失值或负值),而不是像“此页面显示-体重输入无效,输入非负数”这样的警告。换句话说,我想保留相同的消息,但不使用“警告”方法

请问我如何解决这些问题?我在下面附上了我的HTML和CSS代码

非常感谢你

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">  
    <title>BMI Calculation</title>
    <link rel="stylesheet" href="bmi.css">

</head>
<body>
    <main>
        <h2>Body Mass Index Calculation Application</h2>

        <label for="boxHeight">Enter height in inches:</label>
        <input type='text' id='boxHeight'/><br>

        <label for="boxWeight">Enter weight in pounds:</label>
        <input type='text' id='boxWeight'/><br>

        <label>&nbsp;</label>
        <input type="button" id="calculate" value="Calculate">

        <div class="results"></div>

    </main>     
    <script>
        var processEntries = function() {   

             var heightInputBox = document.getElementById("boxHeight");
             var weightInputBox = document.getElementById("boxWeight");
             var outputBMI = document.querySelectorAll("div.results");

             outputBMI[0].textContent = "";
             heightInputBox.className = "";
             weightInputBox.className = "";

             console.log(heightInputBox.getAttribute('class'));

            ///get user input from input box "boxHeight" by using value property, 
            //which return user input as a string               
            //step1.1:get height input and convert height to a number
            var height = heightInputBox.value;
            height = parseFloat(height);

            //step1.2:get weight input and convert weight to a number
            var weight = weightInputBox.value;
            weight = parseFloat(weight);

            var valid = true;           
            if (isNaN(height)||height <0) {
                alert("Invalid input for height, enter a non-negative number.");
                heightInputBox.className = "error";
                valid = false;
            } 

            if (isNaN(weight)||weight <0) {
                alert("Invalid input for weight, enter a non-negative number.");
                weightInputBox.setAttribute('class', "error");
                valid = false;
            }

            if (valid)          //calculate BMI
            {
                outputBMI[0].textContent  ="Your BMI is: " + (703 * weight / (height*height)).toFixed(1);
            if (outputBMI[0]<18.5) outputBMI[0].textContent = "Your BMI indicates that you are underweight.";
            if (outputBMI[0]>=18.5 && outputBMI[0]<=24.99) document.getElementById("result").value = "Normal";
            if (outputBMI[0]>=25 && outputBMI[0]<=29.99) document.getElementById("result").value = "Obese";
            if (outputBMI[0]>30) document.getElementById("result").value = "Overweight";
            }
        };

        //add js code here to handler click event, and make the height input box be focused after the page is opened in web browser
        document.getElementById('calculate').onclick = processEntries;

    </script>
</body>
</html>

你的代码有很多地方需要修改。但底线是,您需要记住,类选择器(在您的例子中是results)总是返回一个数组。如果使用的是唯一的dom,请切换到Id

var processEntries=function(){
var heightInputBox=document.getElementById(“boxHeight”);
var-weightInputBox=document.getElementById(“boxWeight”);
var resultem=document.getElementById(“结果”);
resultElm.textContent=“”;
heightInputBox.className=“”;
weightInputBox.className=“”;
log(heightInputBox.getAttribute('class');
///使用value属性从输入框“boxHeight”获取用户输入,
//它以字符串形式返回用户输入
//步骤1.1:获取高度输入并将高度转换为数字
变量高度=heightInputBox.value;
高度=浮动(高度);
//步骤1.2:获取重量输入并将重量转换为数字
变量权重=weightInputBox.value;
重量=浮点数(重量);
var valid=true;

如果(isNaN(height)| | height我知道这个问题已经有了一个好的、有效的答案

下面是我摆弄小提琴的结果,试图缩短它,使它更“灵敏”

我删除了calculate按钮,现在使用
eval()
对输入字段的值进行适当的转换和计算

const qs=s=>document.querySelector;
evl=s=>{var v='',el=qs(s);
试一试{v=eval(el.value)| |'''}catch(er){v=''}
el.nextElementSibling.innerText=(v?'='+v.toFixed(2):v);
返回v
}
var标度=[[18.5,“减持”],
[25,“正常”],[30,“肥胖”],
[31,“严重超重”];
qs(“body”).addEventListener(“keyup”,ev=>{if(ev.target.type!='text')返回;
var txt,高度=evl(“箱高”),重量=evl(“箱重”);
如果(高度>0和重量>0){
体重指数=703*体重/(身高*身高);
标度:每个(sc=>(txt=sc[1],BMI>sc[0]);
txt='您的BMI为'+BMI.toFixed(1)+''表示您是“+txt+”;
}else txt=“”;
qs(“#结果”).innerHTML=txt
});
正文{
字体系列:Arial、Helvetica、无衬线字体;
背景:url('BMI.jpg')中心固定;
保证金:0自动;
宽度:600px;
边框:3件纯蓝;
}
html{
背景色:#eee;
}
主要{
填充:0 2米1米;
边缘:2米;
背景色:白色;
}
氢{
颜色:蓝色;
}
标签{
浮动:左;
宽度:12em;
文本对齐:右对齐;
垫底:5em;
}
div{
宽度:24em;
文本对齐:左对齐;
垫底:5em;
字体大小:20px;
}
输入{
左边距:1米;
边缘底部:.5em;
}
span{左边距:20px;
字体大小:1.5ex;}

体重指数计算应用
以英寸为单位输入高度:

以磅为单位输入重量:

过了一段时间,我已经编辑了好几次我的代码,我认为这是一个值得分享的版本。我知道还有很多编辑要做,但这里是:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">  
    <title>BMI Calculation</title>
    <link rel="stylesheet" href="bmi.css">

</head>
<body>
    <main>
        <h2>Body Mass Index Calculation Application</h2>

        <label for="boxHeight">Enter height in inches:</label>
        <input type='text' id='boxHeight'/><br>

        <label for="boxWeight">Enter weight in pounds:</label>
        <input type='text' id='boxWeight'/><br>

        <label>&nbsp;</label>
        <input type="button" id="calculate" value="Calculate">

        <div class="results"></div>

    </main>     
    <script>
        var processEntries = function() {   

             var heightInputBox = document.getElementById("boxHeight");
             var weightInputBox = document.getElementById("boxWeight");
             var outputBMI = document.querySelectorAll("div.results");

             outputBMI[0].textContent = "";
             heightInputBox.className = "";
             weightInputBox.className = "";

             console.log(heightInputBox.getAttribute('class'));

            var height = heightInputBox.value;
            height = parseFloat(height);

            var weight = weightInputBox.value;
            weight = parseFloat(weight);

            var valid = true;           
            if (isNaN(height)||height <0 || height != parseInt(height, 10)) {
                outputBMI[0].textContent +=" Invalid input for height, enter a non-negative number.";
                heightInputBox.className = "error";
                valid = false;
            } 

            if (isNaN(weight)||weight <0 || weight != parseInt(weight, 10)) {
                outputBMI[0].textContent +=" Invalid input for weight, enter a non-negative number.";
                weightInputBox.setAttribute('class', "error");
                valid = false;
            }

            if (valid)
            {
                outputBMI[0].textContent  ="Your BMI is: " + (703 * weight / (height*height)).toFixed(1);

                //This is just for my trial and learning process. =)
                var bmi = (703 * weight / (height*height)).toFixed(1);
                if (bmi<18.5) outputBMI[0].textContent += " Your BMI indicates that you are underweight.";
                if (bmi>=18.5 && bmi<=25) outputBMI[0].textContent += "Your BMI indicates that you are normal.";
                if (bmi>25 && bmi<=30) outputBMI[0].textContent += "Your BMI indicates that you are obsese.";
                if (bmi>30) outputBMI[0].textContent += "Your BMI indicates that you are overweight.";
            }
        };

       //handler button click event 
        document.getElementById('calculate').onclick = processEntries;

    </script>
</body>
</html>

体重指数计算
体重指数计算应用
以英寸为单位输入高度:

以磅为单位输入重量:
var processEntries=函数(){ var heightInputBox=document.getElementById(“boxHeight”); var-weightInputBox=document.getElementById(“boxWeight”); var outputBMI=document.querySelectorAll(“div.results”); outputBMI[0]。textContent=“”; heightInputBox.className=“”; weightInputBox.className=“”; log(heightInputBox.getAttribute('class'); 变量高度=heightInputBox.value; 高度=浮动(高度); 变量权重=weightInputBox.value; 重量=浮点数(重量); var valid=true;
如果(isNaN(height)| | height)你的问题有点宽泛,你实际上没有列出任何具体的问题。对你希望程序做什么的描述不是“问题”,这是一项要求。在尝试实现这些要求时,您遇到了哪些问题?请查看。感谢您的回复!我认为最好包括我对该计划的期望-我实际上在下面的描述中列出了我遇到的问题。您最近的编辑删除
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">  
    <title>BMI Calculation</title>
    <link rel="stylesheet" href="bmi.css">

</head>
<body>
    <main>
        <h2>Body Mass Index Calculation Application</h2>

        <label for="boxHeight">Enter height in inches:</label>
        <input type='text' id='boxHeight'/><br>

        <label for="boxWeight">Enter weight in pounds:</label>
        <input type='text' id='boxWeight'/><br>

        <label>&nbsp;</label>
        <input type="button" id="calculate" value="Calculate">

        <div class="results"></div>

    </main>     
    <script>
        var processEntries = function() {   

             var heightInputBox = document.getElementById("boxHeight");
             var weightInputBox = document.getElementById("boxWeight");
             var outputBMI = document.querySelectorAll("div.results");

             outputBMI[0].textContent = "";
             heightInputBox.className = "";
             weightInputBox.className = "";

             console.log(heightInputBox.getAttribute('class'));

            var height = heightInputBox.value;
            height = parseFloat(height);

            var weight = weightInputBox.value;
            weight = parseFloat(weight);

            var valid = true;           
            if (isNaN(height)||height <0 || height != parseInt(height, 10)) {
                outputBMI[0].textContent +=" Invalid input for height, enter a non-negative number.";
                heightInputBox.className = "error";
                valid = false;
            } 

            if (isNaN(weight)||weight <0 || weight != parseInt(weight, 10)) {
                outputBMI[0].textContent +=" Invalid input for weight, enter a non-negative number.";
                weightInputBox.setAttribute('class', "error");
                valid = false;
            }

            if (valid)
            {
                outputBMI[0].textContent  ="Your BMI is: " + (703 * weight / (height*height)).toFixed(1);

                //This is just for my trial and learning process. =)
                var bmi = (703 * weight / (height*height)).toFixed(1);
                if (bmi<18.5) outputBMI[0].textContent += " Your BMI indicates that you are underweight.";
                if (bmi>=18.5 && bmi<=25) outputBMI[0].textContent += "Your BMI indicates that you are normal.";
                if (bmi>25 && bmi<=30) outputBMI[0].textContent += "Your BMI indicates that you are obsese.";
                if (bmi>30) outputBMI[0].textContent += "Your BMI indicates that you are overweight.";
            }
        };

       //handler button click event 
        document.getElementById('calculate').onclick = processEntries;

    </script>
</body>
</html>