Как создать калькулятор ИМТ, используя JavaScript с возможностью выбора между ИМТ в килограммах / метрах или ИМТ в фунтах / футах - PullRequest
0 голосов
/ 16 февраля 2020

Добрый день всем,

В настоящее время я пишу калькулятор ИМТ для своего проекта. Калькулятор уже настроен на работу в фунтах / футах, но я хотел бы добавить опцию, в которой я могу выбирать между килограммами / метрами или фунтами / футами.

Я создал код html для этого и просто нужна JavaScript часть, чтобы заставить его работать.

Обратите внимание, что формула, используемая для Lbs:

((mass / 2.2046) / ((height/3.28) * (height/3.28))).toFixed(2)

И если бы я хотел вычислить ИМТ в килограммах / метрах, для формулы будет:

(mass / (height * height)).toFixed(2)

Пожалуйста, посмотрите ниже, что я сделал до сих пор: Ваша помощь всегда ценится. Заранее спасибо.

// BMI Calculator
  
const myForm     = document.getElementById('my-form');

myForm.oninput = () => {
    myForm.result.value = bmiCalculator(myForm.height.value, myForm.mass.value);


function bmiCalculator(height, mass)  {   
    return ((mass / 2.2046) / ((height/3.28) * (height/3.28))).toFixed(2)

    }
}
 fieldset { margin-top: 1em;
}
 label { 
   display: inline-block; width: 10em; text-align: left; 
  }
  input { 
    font-size: .9em; text-align: left; display: inline-block; width: 10em;
  }
   output::before {  
     content: ''; 
  }
  output { 
      font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
  }
  append { 
      display: inline-block; width: 10em; text-align: center; 
  }
<h2>Body Mass Index Calculator</h2>

  <!-- Used oninput to display the results instantly-->
  <!-- If I wanted to calculate the result on a click, I would use onsubmit-->

  <form action="" oninput="return mySubmitFunction(event)" id="my-form">

    <fieldset>
     <legend>Please Choose which BMI you would like to use :</legend>
     <append>BMI in Kgs / Meters <input type="radio" name="bmi" value="bmiInKgs"></append>
     <append>BMI in Lbs / Feet <input type="radio" name="bmi" value="bmiInLbs"></append>
    </fieldset>

    <fieldset>
    <fieldset>
      <legend><b>Calculate Your BMI :</b></legend>
      <br>
     <label>Height in Feet: <input type="number" id="height" name="height" step=any min=0></label>
      <label>Mass / Weight in lbs: <input type="number" id="mass" class="mass" step=any min=0></label> 
    </fieldset>
    
    
    <fieldset><br>
      <legend><b>BMI Result  :</b></legend>
      <output id="result" name="result" value='0'></output>
  
      <br><br>
      <button type="reset">Reset Calculator!</button>
    </fieldset></fieldset>
  </form>

1 Ответ

1 голос
/ 16 февраля 2020

Если я понимаю, все, что вам нужно, это получить доступ к значению радио, правильно?

if (myForm.bmi.value == "bmiInKgs")
  // Calculate Kg
else {
  // Calculate Lbs
} 

// BMI Calculator
  
const myForm     = document.getElementById('my-form');

myForm.oninput = () => {
if (myForm.bmi.value == "bmiInKgs") {
    myForm.result.value = bmiCalculator(myForm.height.value, myForm.mass.value);
} else {
    myForm.result.value = bmiCalculator(myForm.height.value/3.28, myForm.mass.value/2.2046);
}

function bmiCalculator(height, mass)  {   
    return (mass / (height * height)).toFixed(2)
    }
}
fieldset { margin-top: 1em;
}
 label { 
   display: inline-block; width: 10em; text-align: left; 
  }
  input { 
    font-size: .9em; text-align: left; display: inline-block; width: 10em;
  }
   output::before {  
     content: ''; 
  }
  output { 
      font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
  }
  append { 
      display: inline-block; width: 10em; text-align: center; 
  }
<h2>Body Mass Index Calculator</h2>

  <!-- Used oninput to display the results instantly-->
  <!-- If I wanted to calculate the result on a click, I would use onsubmit-->

  <form action="" oninput="return mySubmitFunction(event)" id="my-form">

    <fieldset>
     <legend>Please Choose which BMI you would like to use :</legend>
     <append>BMI in Kgs / Meters <input type="radio" name="bmi" value="bmiInKgs" checked="checked"></append>
     <append>BMI in Lbs / Feet <input type="radio" name="bmi" value="bmiInLbs"></append>
    </fieldset>

    <fieldset>
    <fieldset>
      <legend><b>Calculate Your BMI :</b></legend>
      <br>
     <label>Height: <input type="number" id="height" name="height" step=any min=0></label>
      <label>Mass / Weight: <input type="number" id="mass" class="mass" step=any min=0></label> 
    </fieldset>
    
    
    <fieldset><br>
      <legend><b>BMI Result  :</b></legend>
      <output id="result" name="result" value='0'></output>
  
      <br><br>
      <button type="reset">Reset Calculator!</button>
    </fieldset></fieldset>
  </form>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...