Программа расчета ИМТ - PullRequest
0 голосов
/ 06 октября 2019

Я создал приложение для расчета ИМТ. По сути, вот как я хотел бы, чтобы приложение работало, и написал ниже:

  • Вы просто вводите свой рост в дюймах и вводите вес в фунтах.

  • Приложение рассчитает ваш ИМТ, а затем сообщит вам, есть ли у вас недостаточный вес, нормальный вес, ожирение или избыточный вес.

  • В случае ввода неположительного значения длябудь то рост или вес, программа покажет вам сообщение об ошибке «Неверный ввод. Введите положительное число» и выделит поля, которые необходимо исправить / ввести правильное значение.

Я столкнулся с двумя проблемами.

  • Я могу заставить программу показать результат BMI, но в настоящее время я не знаю, как писать вполучить программу, показывающую, имеет ли пользователь недостаточный вес, нормальный, ожирение или избыточный вес. Если ИМТ <18,5, то недостаточный вес, ИМТ> = 18,5 и <= 24,99, то нормальный, ИМТ> 25 и <= 29,99, затем ожирение, и ИМТ> 30, а затем избыточный вес.

  • Я хотел бы показать ошибку (которая говорит пользователю вводить положительные значения, а не пропущенные или отрицательные значения) в виде сообщений под кнопкой «Рассчитать ИМТ», а не как предупреждениеНа этой странице написано - Неверный ввод веса, введите неотрицательное число. "Другими словами, я хотел бы сохранить то же сообщение, но не используя метод «alert».

Как я могу исправить эти проблемы, пожалуйста? Ниже я приложил и мой 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>

Вот и мой CSS-код, если вам это нужно:

article, aside, figure, footer, header, main, nav, section {
    display: block;
}
body {
    font-family: Arial, Helvetica, sans-serif;
    background: url('BMI.jpg') center center fixed;

    margin: 0 auto;
    width: 600px;
    border: 3px solid blue;

}
html {
    background-color: #eee;
}
main {
    padding: 0 2em 1em;
    margin: 2em;
    background-color: white;

}
h2 {
    color: blue;
}
label {
    float: left;
    width: 12em;
    text-align: right;
    padding-bottom: .5em;
}

div {
    width: 24em;
    text-align: left;
    padding-bottom: .5em;   
    font-size: 20px;

}

input {
    margin-left: 1em;
    margin-bottom: .5em;

}
input.error {
    background-color: #FFFF00;
    border: 2px solid #fe9772;
}

Ответы [ 3 ]

1 голос
/ 06 октября 2019

В вашем коде многое нужно переделать. Но суть в том, что вам нужно помнить, что classSelector (в вашем случае результат) всегда возвращает массив. Переключитесь на Id, если вы используете уникальный домен

var processEntries = function() {   

             var heightInputBox = document.getElementById("boxHeight");
             var weightInputBox = document.getElementById("boxWeight");
             var resultElm = document.getElementById("result");

             resultElm.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;
            }
            var bmi = 703 * weight / (height** 2)
            if (valid)          //calculate BMI
            {
                resultElm.textContent  ="Your BMI is: " + (bmi).toFixed(1);
                if (bmi<18.5) resultElm.textContent += " Your BMI indicates that you are underweight.";
                if (bmi>=18.5 && bmi<=25) resultElm.textContent += " Your BMI indicates that you are Normal.";
                if (bmi>=25 && bmi<=30)resultElm.textContent += " Your BMI indicates that you are Obese.";
                if (bmi>30) resultElm.textContent += " Your BMI indicates that you are 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;
article, aside, figure, footer, header, main, nav, section {
    display: block;
}
body {
    font-family: Arial, Helvetica, sans-serif;
    background: url('BMI.jpg') center center fixed;

    margin: 0 auto;
    width: 600px;
    border: 3px solid blue;

}
html {
    background-color: #eee;
}
main {
    padding: 0 2em 1em;
    margin: 2em;
    background-color: white;

}
h2 {
    color: blue;
}
label {
    float: left;
    width: 12em;
    text-align: right;
    padding-bottom: .5em;
}

div {
    width: 24em;
    text-align: left;
    padding-bottom: .5em;   
    font-size: 20px;

}

input {
    margin-left: 1em;
    margin-bottom: .5em;

}
input.error {
    background-color: #FFFF00;
    border: 2px solid #fe9772;
    }
<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 id="result"></div>

    </main>
0 голосов
/ 07 октября 2019

Через некоторое время я несколько раз редактировал свой код, и я думаю, что стоит поделиться этой версией. Я знаю, что есть еще какие-то правки, но вот они:

<!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>
0 голосов
/ 07 октября 2019

Я знаю, что на этот вопрос уже есть хороший и действительный ответ.

Следующее - просто результат того, что я играю с скрипкой, пытаюсь сократить ее и сделать ее более "отзывчивой".

Я удалил кнопку вычисления и теперь использую eval(), чтобы допускать точное преобразование и вычислять значения полей ввода.

const qs=s=>document.querySelector(s);
evl=s=>{var v='', el=qs(s);
 try{v=eval(el.value)||''} catch(er){v=''}
 el.nextElementSibling.innerText=(v?'='+v.toFixed(2):v);
 return v
}
var scale=[[18.5,"underweight"],
 [25,"normal"],[30,"obese"],
 [31,"seriously overweight"]];
 
qs("body").addEventListener("keyup",ev=>{if(ev.target.type!='text') return;
 var txt, height=evl("#boxHeight"), weight=evl("#boxWeight");
 if (height>0 && weight>0){
   BMI=703*weight/(height*height);
   scale.every(sc=>(txt=sc[1],BMI>sc[0])); 
   txt='Your BMI of '+BMI.toFixed(1)+" indicates<br>that you are "+txt+".";
 } else txt='';
 qs("#result").innerHTML=txt
 
});
body {
    font-family: Arial, Helvetica, sans-serif;
    background: url('BMI.jpg') center center fixed;

    margin: 0 auto;
    width: 600px;
    border: 3px solid blue;

}
html {
    background-color: #eee;
}
main {
    padding: 0 2em 1em;
    margin: 2em;
    background-color: white;
}
h2 {
    color: blue;
}
label {
    float: left;
    width: 12em;
    text-align: right;
    padding-bottom: .5em;
}
div {
    width: 24em;
    text-align: left;
    padding-bottom: .5em;   
    font-size: 20px;
}

input {
    margin-left: 1em;
    margin-bottom: .5em;

}
span {margin-left:20px;
      font-size:1.5ex;}
<main>
        <h2>Body Mass Index Calculation Application</h2>

        <label for="boxHeight">Enter height in inches:</label>
        <input type='text' id='boxHeight' placeholder="value or formula"/><span id="one"></span><br>

        <label for="boxWeight">Enter weight in pounds:</label>
        <input type='text' id='boxWeight' placeholder="value or formula"/><span id="two"></span><br>
        <div id="result"></div>
    </main>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...