Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

190
Visualizações
Using JS to show HTML output of calculation

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>

over 4 years ago · Santiago Trujillo
6 Respostas
Responde à pergunta

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>

over 4 years ago · Santiago Trujillo Relatório

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);
}
over 4 years ago · Santiago Trujillo Relatório

0

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>

over 4 years ago · Santiago Trujillo Relatório

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>

over 4 years ago · Santiago Trujillo Relatório

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>

over 4 years ago · Santiago Trujillo Relatório

0

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
    }

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda