skip to Main Content

I am new in webdev and now learning to make new and small projects using HTML, CSS and Javascript.
I have made a simple BMI calculator. In the calculator when a user supposed to give all the necessary inputs then clicking on a button it supposed to show the results after calculating that.

I have done this using HTML form. The index.html file is:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>BMI Calculator</title>
  </head>
  <body>
    <div class="container">
      <h2>BMI Calculator</h2>
      <form id="BMIForm">
        <label for="gender">Gender: </label>
        <select id="gender" required>
          <option value="Male">Male</option>
          <option value="Female">Female</option>
          <option value="Third Gender">Third Gender</option>
        </select>

        <label for="age">Age:</label>
        <input type="number" id="age" placeholder="Enter Age" required />

        <label for="height-feet">Height:</label>
        <input type="number" id="heigt-feet" placeholder="Feet" required />
        <input type="number" id="height-inches" placeholder="inches" />

        <label for="weight">Weight: </label>
        <input type="number" id="weight" placeholder="Enter Weight in Kgs" />

        <input type="submit" value="Calculate BMI" />
      </form>

      <div id="result"></div>
    </div>

    <script src="script.js"></script>
  </body>
</html>

and the style.css file is this:

body{
    background-color: rgba(104, 3, 163, 0.801);
}

.container {
    max-width: 400px;
    margin: 200px auto;
    padding: 20px;
    background-color: #da6161;
    border: 2px solid rgb(255, 255, 255);
    border-radius: 20px;
    box-shadow: 10px 10px 10px rgba(1, 1, 1, 0.6);
    
}

h2 {
    margin-top: 0;
    color: #3a3838;
    text-align: center;
    text-decoration:underline ;

}

form {
    margin-bottom: 50px;
    display:flex;
    flex-direction:column;
}

label {
    font-size:larger;
    font-weight: 1000px;
    margin-bottom: 5px;
    color: #ffffff;
}

input[type="number"],
select {

    width: 95%;
    padding: 10px;
    border: none;
    background-color: #caadad;
    border-radius: 10px;
    box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);
    margin-bottom: 10px;
}

input[type="number"] :focus,
select :focus {
    outline: none;
    box-shadow: 0px 0px 0px 5px rgb(0, 0, 0);

}

select {
    width: 100%;
}

input[type="submit"]{
    padding: 10px;
    margin-top: 10px;
    background-color: rgb(2, 4, 92);
    border: none;
    border-radius: 50px;
    color: #fdfdfd;
    cursor: pointer;
    transition: background-color 0.1s ease;

}

input[type="submit"]:hover {
    background-color: blueviolet;
}

#result {
    font-weight: bold;
    margin-top: 10px;
    color: black;
}


But I think there are some issues with the Javascript file – script.js:

document.getElementById('BMIForm').addEventListener('submit',function(e){
    e.preventDefault(); //it will help to not refresh automatically

    const gender = document.getElementById('gender').value;
    const age = parseInt(document.getElementById('age').value); // type conversion because html generates string numbers what needs to be converted to string. 
    const heightFeet = parseInt(document.getElementById('height-feet').value);
    const heightInches = parseInt(document.getElementById('heigh-inches').value);
    const weight = parseFloat(document.getElementById('weight').value);



    if(gender && age && heightFeet && heightInches && weight){

        const heightInMeters = (heightFeet * 12 + heightInches) * 0.0254; // height in meters
        const bmi = weight / (heightInMeters*heightInMeters);
        const resultElement = document.getElementById('result');

        let category = '';

        if(bmi < 18.5){
            category = 'Under Weight';
        }else if(bmi >= 18.5 && bmi < 25){
            category = 'Normal Weight';
        }else if(bmi >= 25 && bmi < 30){
            category = 'Over Weight';
        }else{
            category += 'Obese';
        }


        let resultMessage = 'Your BMI: ' + bmi.toFixed(2) + '<br>';

        resultMessage += 'Category: ' + category;


        resultElement.innerHTML = resultMessage;
    }

});

In this script.js file the rendering of the last line:resultElement.innerHTML = resultMessage; which is supposed to render a message is not showing after clicking the button even.

Before giving any input:
Before giving any input:

After giving input and clicking on the hovering button No result is showing:
enter image description here

Can anyone help me find out where the bug is?

#TIA

I am new in webdev and now learning to make new and small projects.
I have tried to make a simple BMI calculator using HTML, CSS and Javascript. In the calculator when a user supposed to give all the necessary inputs then clicking on a button it supposed to show the results after calculating that. But nothing is showing.

3

Answers


  1. You misspelt the word height in certain places, I have corrected it. You can right-click on the browsers like chrome/edge and go to inspect->console to see any errors in JavaScript

    index.html

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <link rel="stylesheet" href="style.css" />
            <title>BMI Calculator</title>
        </head>
        <body>
            <div class="container">
                <h2>BMI Calculator</h2>
                <form id="BMIForm">
                    <label for="gender">Gender: </label>
                    <select id="gender" required>
                        <option value="Male">Male</option>
                        <option value="Female">Female</option>
                        <option value="Third Gender">Third Gender</option>
                    </select>
                    <label for="age">Age:</label>
                    <input type="number" id="age" placeholder="Enter Age" required />
                    <label for="height-feet">Height:</label>
                    <input type="number" id="height-feet" placeholder="Feet" required />
                    <input type="number" id="height-inches" placeholder="inches" />
                    <label for="weight">Weight: </label>
                    <input type="number" id="weight" placeholder="Enter Weight in Kgs" />
                    <input type="submit" value="Calculate BMI" />
                </form>
                <div id="result"></div>
            </div>
            <script src="script.js"></script>
        </body>
    </html>
    

    script.js

    document.getElementById('BMIForm').addEventListener('submit',function(e){
        e.preventDefault(); //it will help to not refresh automatically
        
        const gender = document.getElementById('gender').value;
        const age = parseInt(document.getElementById('age').value); // type conversion because html generates string numbers what needs to be converted to string. 
        const heightFeet = parseInt(document.getElementById('height-feet').value);
        const heightInches = parseInt(document.getElementById('height-inches').value);
        const weight = parseFloat(document.getElementById('weight').value);
    
        if(gender && age && heightFeet && heightInches && weight){
    
            const heightInMeters = (heightFeet * 12 + heightInches) * 0.0254; // height in meters
            const bmi = weight / (heightInMeters*heightInMeters);
            const resultElement = document.getElementById('result');
    
            let category = '';
    
            if(bmi < 18.5){
                category = 'Under Weight';
            }else if(bmi >= 18.5 && bmi < 25){
                category = 'Normal Weight';
            }else if(bmi >= 25 && bmi < 30){
                category = 'Over Weight';
            }else{
                category += 'Obese';
            }
    
    
            let resultMessage = 'Your BMI: ' + bmi.toFixed(2) + '<br>';
    
            resultMessage += 'Category: ' + category;
    
            resultElement.innerHTML = resultMessage;
        }
    
    });
    
    Login or Signup to reply.
  2. I’d avoid using <input type=“submit” … unless you also intend to submit the form to your web server. Instead, a “button” would suffice:

        <input type="button” id=“bmiCalcButton” onclick=“CalculateBMI()" value="Calculate BMI" />
    

    Then you can use the onclick= attribute to reference a JavaScript function by name, or add the event listener to the button’s click event by ID.

    Login or Signup to reply.
  3. As a little "Sunday morning at breakfast and nothing else to do" exercise I rewrote your BMI calculator. I tried to avoid redundancies in the code but in some aspects the following might now seem a little hard to read 😀 …

    const scale=[[30,"obese"],[25,"over weight"],[18.5,"normal weight"],[0,"underweight"]];
    const inps=[hgt,wgt]=document.querySelectorAll("input"),
     [mh,mw,res]=["mheight","mweight","result"].map(el=>document.getElementById(el));
    inps.forEach(el=>el.addEventListener("input",()=>{
     const [feet, inches]=hgt.value.split(/s+/),
      [stones, pounds]=wgt.value.split(/s+/),
      wkg=(stones*14+ +(pounds??0))*0.453592,
      hm=(feet*12+ +(inches??0))*.0254,
      bmi=hm?wkg/hm**2:null;
     mh.textContent=hm.toFixed(2)+"m";
     mw.textContent=wkg.toFixed(2)+"kg";
     res.innerHTML="Your BMI of "+bmi.toFixed(2)+"<br>classifies you as "+scale.find(b=>b[0]<bmi)?.[1];
    }));
    <input type="text" placeholder="height in feet and inches"><span id="mheight"></span><br>
    <input type="text" placeholder="weight in stones and pounds"><span id="mweight"></span>
    <div id="result"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search