4

I am trying to build a calorie calculator using HTML and JS and am currently struggling to show the output on screen (or via console.log). I know I'm doing something very basic quite wrong but can't currently pinpoint what that is.

Here's both my HTML and JS code below:

document.getElementById("bmrForm").addEventListener("submit", calcBMR);
    
    function calcBMR(gender, weightKG, heightCM, age) {
    
        // Calculate BMR
        if (gender = 'male') {
            let BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
        } else {
            let BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
        }
    
        console.log(BMR);
    }
    <body>
    <script src="./script.js"></script>
    <section>
        <form id="bmrForm" onsubmit="calcBMR()">
            <input type="text" id="gender" placeholder="Male or female?">
            <input type="number" id="weight" placeholder="Weight in KG">
            <input type="number" id="height" placeholder="Height in CM">
            <input type="number" id="age" placeholder="How old are you?">
            <button type="submit" id="submitBtn">Do Magic!</button>
        </form>
        <p id="output">0</p>
    </section>
</body>

1
  • html "Form" brief tutorial; Important: there's a link for <input> types - read that too. Anyway,Submit button has a special purpose and unless you understand event propagation (note preventDefault in some answers) use a basic type=button instead.
    – radarbob
    Jan 21, 2022 at 19:59

7 Answers 7

2

Several things need to be modified in order to achieve your desired result.

  1. The line document.getElementById("bmrForm").addEventListener("submit", calcBMR); is not needed because we can pass in a function directly to the onsubmit attribute of the form element.
  2. The gender, weightKG, heightCM, and age parameters are not automatically passed in to the calcBMR function. The values need to be retrieved from the document.
  3. The BMR variable needs to be defined above the if/else block because of scoping.
  4. A return statement needs to be added to the onsubmit attribute so that the form does not submit and refresh the page. Alternatively, if the desired effect is to update the text on the screen, a button element with a click event handler added to it may be a better option that a form with a submit handler.
  5. Strings are compared using == or === in JavaScript. Therefore, the gender = 'male' part needs to be changed to gender === 'male'.
  6. In order to update the output, the element's textContent can be changed with document.getElementById("output").textContent = BMR.

Below is the code with the changes listed above.

function calcBMR() {
    let gender = document.getElementById("gender").value;
    let weightKG = document.getElementById("weight").value;
    let heightCM = document.getElementById("height").value;
    let age = document.getElementById("age").value;
    let BMR;
    // Calculate BMR
    if (gender === 'male') {
        BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
    } else {
        BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
    }

    console.log(BMR);
    document.getElementById("output").textContent = BMR;
    return false;
}
<body>
<script src="./script.js"></script>
<section>
    <form id="bmrForm" onsubmit="return calcBMR()">
        <input type="text" id="gender" placeholder="Male or female?">
        <input type="number" id="weight" placeholder="Weight in KG">
        <input type="number" id="height" placeholder="Height in CM">
        <input type="number" id="age" placeholder="How old are you?">
        <button type="submit" id="submitBtn">Do Magic!</button>
    </form>
    <p id="output">0</p>
</section>

3
  • innerHTML should be avoided when possible (which is most of the time) due to security and performance implications. Use textContent instead. Jan 21, 2022 at 19:35
  • @ScottMarcus Agreed, updated.
    – wahoowa
    Jan 21, 2022 at 19:47
  • Using inline event listeners is also discouraged (OP's addEventListener is actually the preferred way).
    – FZs
    Jan 21, 2022 at 20:08
2

First, you are using a button with a type="submit", which is used to submit form data to a resource that will receive it and process it. In this case, you probably just want a button with type="button" that will only do what you've configured it to do (show the results on the screen).

After making that change, you should populate a pre-existing, but empty element with the result.

But you do have an issue with how and where you are declaring BMR. The let declaration should be outside of the if/then code but inside the function so it has scope throughout the function.

Also, your button's id is incorrect in the event handler setup.

Next, any value that you get from an HTML element will be a string and if you intend to do math with that value, you'll need to convert it to a JavaScript number. There are several ways to do this, but one shorthand way is to prepend the value with a + as you'll see I've done below.

Also, if someone were to type Male into the gender textbox, your code would not process it as a male because your code only checks for male, not Male. By forcing the input to lower case, your code will work (provided they spell male correctly). Preferably, you'd use a set of radio buttons or a drop down list for the user to choose from.

And, in conjunction with that, JavaScript uses = for assigning a value, not comparison. For loose equality (automatic type conversion) use == and for strict equality (no type conversion), use ===.

let out = document.getElementById("output");
let gender = document.getElementById("gender");
let height = document.getElementById("height");
let weight = document.getElementById("weight");
let age = document.getElementById("age");

// If you want to pass arguments to the event handler, you need to wrap the handler call in another function
document.getElementById("submitBtn").addEventListener("click", function(){calcBMR(gender.value.toLowerCase(), +weight.value, +height.value, +age.value)});
    
    function calcBMR(gender, weightKG, heightCM, age) {
        let BMR = null;  // Declare the variable in the function scope
        console.log(gender, weightKG, heightCM, age);
    
        // Calculate BMR
        if (gender === 'male') {
            BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
        } else {
            BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
        }
    
        console.log(BMR);
        output.textContent = BMR;
        
    }
<body>
    <script src="./script.js"></script>
    <section>
        <form id="bmrForm" onsubmit="calcBMR()">
            <input type="text" id="gender" placeholder="Male or female?">
            <input type="number" id="weight" placeholder="Weight in KG">
            <input type="number" id="height" placeholder="Height in CM">
            <input type="number" id="age" placeholder="How old are you?">
            <button type="button" id="submitBtn">Do Magic!</button>
        </form>
        <p id="output">0</p>
    </section>
</body>

2

Working Codepen

There are a few fundamental flaws in your code. Having said that, studying this will really give you a proper understanding of Javascript.

HTML:

 <body>
    <section>
        <form id="bmrForm">
            <input type="text" id="gender" placeholder="Male or female?" name="gender">
            <input type="number" id="weight" placeholder="Weight in KG" name="weight">
            <input type="number" id="height" placeholder="Height in CM" name="height">
            <input type="number" id="age" placeholder="How old are you?" name="age">
            <button type="submit" id="submitBtn">Do Magic!</button>
        </form>
        <p id="output">0</p>
    </section>
</body>

Javascript:

document.getElementById("bmrForm").addEventListener("submit", calcBMR);
const output = document.querySelector('#output')
    
function calcBMR(e) {
      e.preventDefault();
  
  output.innerText = ''
  const formData = new FormData(e.target)
  const { age, gender, height, weight} = Object.fromEntries(formData);

      let BMR  = 0
        // Calculate BMR
        if (gender === 'male') {
            BMR = 10 * parseInt(weight) + 6.25 * parseInt(height) - 5 * parseInt(age) + 5;
        } else {
             BMR = 10 * parseInt(weight) + 6.25 * parseInt(height) - 5 * parseInt(age) - 161;
        }
    
        output.innerText = BMR
    }

1
  • 1
    There's a lot wrong here. A form's submit event that is prevented without any code to submit the form data is nothing more than a click event and therefore a button of type="button" should be used without any form in the first place. innerText should not be used, rather textContent should and if you are going to use parseInt, you should always supply the second argument (radix). Jan 24, 2022 at 14:56
0

You can remove the line document.getElementById("bmrForm").addEventListener("submit", calcBMR);

You can pass event to onsubmit - <form id="bmrForm" onsubmit="calcBMR(event)">

function calcBMR(e) {
e.preventDefault();
var elements = document.getElementById("bmrForm").elements; // logic to get all form elements
var obj ={};
for(var i = 0 ; i < elements.length ; i++){
    var item = elements.item(i);
    obj[item.id] = item.value;
}
const {gender, weight, height, age } = obj; //Get values from obj
// Calculate BMR
let BMR = '';
if (gender === 'male') {
    BMR = 10 * weight + 6.25 * height - 5 * age + 5;
} else {
    BMR = 10 * weight + 6.25 * height - 5 * age - 161;
}
console.log(BMR);
}
1
  • Using inline event listeners is discouraged (OP's addEventListener is actually the preferred way).
    – FZs
    Jan 21, 2022 at 20:12
0

The BMR is in the if tree, it must be in parent.

Try this!

document.getElementById("bmrForm").addEventListener("submit", calcBMR);

const output = document.getElementById('output');

function calcBMR(event) {
    // Get the [gender, weightKG, heightCM, age] value
    let gender = document.getElementById('gender').value;
    let weightKG = document.getElementById('weight').value;
    let heightCM = document.getElementById('height').value;
    let age = document.getElementById('age').value;

    // Set default BMR to 0
    let BMR = 0;
    // Calculate BMR
    if (gender = 'male') {
        BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
    } else {
        BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
    }

    console.log(BMR);
    output.innerText = BMR;

    // Cancel form submit
    event.preventDefault();
    return;
}
<body>
    <script src="./script.js"></script>
    <section>
        <form id="bmrForm">
            <input type="text" id="gender" placeholder="Male or female?">
            <input type="number" id="weight" placeholder="Weight in KG">
            <input type="number" id="height" placeholder="Height in CM">
            <input type="number" id="age" placeholder="How old are you?">
            <button type="submit" id="submitBtn">Do Magic!</button>
        </form>
        <p id="output">0</p>
    </section>
</body>

0

I used a selector instead of the text field for the gender.
I used form.elements to get the values from the form.
I used event.preventDefault(); to prevent the form from redirecting on submit.

// your form
var form = document.getElementById("formId");

var DoMagic = function(event) 
{
  event.preventDefault();
  var elements = form.elements;
  if (elements["gender"].value == "male") 
  {
    var result = 10 * elements["weight"].value + 6.25 * elements["height"].value - 5 * elements["age"].value + 5;
  }
  else 
  {
    var result = 10 * elements["weight"].value + 6.25 * elements["height"].value - 5 * elements["age"].value - 161;
  }
  document.getElementById("result").textContent = "Result: " + result;
}

// attach event listener
form.addEventListener("submit", DoMagic, true);
<form id = "formId">
  <label>Gender</label>
  <select name="gender">
    <option value="male">Male</option>
    <option value="female">Female</option>
  </select>
  <br>
  <label>Weight (kg)</label>
  <input name="weight" type="number">
  <br>
  <label>Height (cm)</label>
  <input name="height" type="number">
  <br>
  <label>Age (years)</label>
  <input name="age" type="number">
  <br>
  <input type="submit" value="Do Magic!">
</form>
<span id='result'> </span>

0

Try this one, you are almost done, just by getting value from the input when user clicks the button.

But I have to notice you that submit button will immediately redirect to a new page, you should use click instead if you want to show yourself result.

document.getElementById("submitBtn").addEventListener("click",function(){
let gen = document.querySelector('#gender').value
   let weight = document.querySelector('#weight').value
    let height = document.querySelector('#height').value
     let ages = document.querySelector('#age').value
calcBMR(gen,weight,height,ages)
})
    function calcBMR(gender, weightKG, heightCM, age) {
       let BMR
        // Calculate BMR
        if (gender = 'male') {
            BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
        } else {
            BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
        }
    
        document.querySelector('#output').textContent = BMR;
    }
<body>
    <script src="./script.js"></script>
    <section>
        <form id="bmrForm">
            <input type="text" id="gender" placeholder="Male or female?">
            <input type="number" id="weight" placeholder="Weight in KG">
            <input type="number" id="height" placeholder="Height in CM">
            <input type="number" id="age" placeholder="How old are you?">
            <button id="submitBtn">Do Magic!</button>
        </form>
        <p id="output">0</p>
    </section>
</body>

2
  • BMR doesn't have to be global
    – FZs
    Jan 21, 2022 at 20:10
  • @FZs, updated it:)
    – James
    Jan 21, 2022 at 20:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.