Home > database >  Passing data from an html form into a Javascript object
Passing data from an html form into a Javascript object

Time:11-28

I want to build a simple TDEE calculator using Javascript.

I want the user to fill in their details in a html form and then pass that info into a Javascript object.

See my HTML code below, where I created the form;

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>TDEE</title>
    <link rel = "stylesheet" href="style.css">
  </head>
  <body>
    <form id="tdeeCalc">
      <label for="gender">Gender:</label>
      <select id="gender" name="gender">
        <option value="Male">Male</option>
        <option value="Female">Female</option>
      </select>
      <br>
        <label for="Weight-Unit">Weight Unit:</label>
        <select id="weight-unit" name="weight-unit">
          <option value="kg">kg</option>
          <option value="lb">lb</option>
        </select>
      <br>
      <label for="Weight">Weight</label>
      <input type="number" id="weight" name="weight">
      <br>
      <label for="Height-Unit">Height Unit:</label>
      <select id="height-unit" name="height-unit">
        <option value="cm">cm</option>
        <option value="in">in</option>
      </select>
      <br>
      <label for="Height">Height</label>
      <input type="number" id="height" name="height">
      <br>
      <label for="Age">Age</label>
      <input type="number" id="age" name="age">
      <br>
      <input type="submit" value="Submit">
  </form>

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

See my JS code where I want to use the users submitted info to calculate their TDEE

`

const user = {};

//Function To Store the Users TDEE And Display It To The Console
const tdeeResult = function (){
  if (user.gender === 'male'){
    user.tdee = maleTdee();   
    }
    else if (user.gender === 'female'){
    user.tdee = femaleTdee(); 
  }
  return console.log(`As a ${user.age} year old ${user.gender} weighing ${user.weight}${user.weightUnit} and with a height of ${user.height}${user.heightUnit} your TDEE is ${user.tdee}`);;
}

// Get reference to the form element
const myTdeeForm = document.getElementById("tdeeCalc")

// Intialise FormData constructor with myTdeeForm
myTdeeForm.addEventListener('submit', (e)=>{
    e.preventDefault();

    // Using formData.entries() and Object.fromEntries() method to convert the form data into a valid javascript object
    const tdeeFormData = new FormData(myTdeeForm);

   const user = Object.fromEntries(tdeeFormData.entries())

   tdeeResult(user);

});

//Declaring User Details
// const user = {
//   gender: 'female',
//   weight: 100,
//   height: 182.88,
//   age: 30,
//   weightUnit: 'kg',
//   heightUnit: 'cm',
//   tdee: 0,
// }

//Function To Convert Lbs To Kgs
const poundsConversion = function () {
  return user.weight / 2.2046
}

//Function To Convert Inches To Cm
const inchesConversion = function () {
  return user.height * 2.54
}

//If Statement To Convert User Weight If Specified in Lbs
if (user.weightUnit !== 'kg'){
  user.weight = poundsConversion(user.weight);
  //console.log(user.weight);
}

//If Statement To Convert User Weight If Specified in Inches
if (user.heightUnit !== 'cm'){
 user.height = inchesConversion(user.height);
 //console.log(user.height);
}

//Function To Calculate TDEE For Males
const maleTdee = function (){
  return 66   (13.7 * user.weight)   (5 * user.height) - (6.8 * user.age);
}


//Function To Calculate TDEE For Females
const femaleTdee = function (){
  return 655   (9.6 * user.weight)   (1.8 * user.height) - (4.7 * user.age);
}

`

When I run the code the following message is logged to the console;

As a undefined year old undefined weighing NaNundefined and with a height of NaNundefined your TDEE is undefined

Why arent the form details being passed into the user object?

If I console log the user it does seem they are being captured but why isnt this accessible by the function?

CodePudding user response:

You are giving your tdeeResult function a new user object as parameter, but the function does not define any parameter.

Either provide the user as a parameter of each of your functions that needs it (which is better for readability in my opinion) or modify the global user variable in the event listener.

CodePudding user response:

The html is correct. In the JavaScript I found several problems, the html is fine, but the main one is the use of the user constant initialized at the beginning of the code, the problem is a matter of scope since in the submit event of the form it is initializing it again with the form data, the constant initialized at the beginning of the code, and the constant initialized in the form's submit event do not share their value. When executing the "tdeeResult" function in the sending event, it is passing the "user" constant as a parameter but in the function declaration it is not receiving it. There are also problems with the if statements in charge of converting the weight and height depending on the measurement units.

const tdeeResult = function (user){
  user.weight = poundsConversion(user.weight);
  user.height = poundsConversion(user.height)
  if (user.gender === 'Male'){
    user.tdee = maleTdee(user);   
    }
    else if (user.gender === 'Female'){
    user.tdee = femaleTdee(user); 
  }
  console.log(user.tdee)
  console.log(`As a ${user.age} year old ${user.gender} weighing ${user.weight}${user.weightUnit} and with a height of ${user.height}${user.heightUnit} your TDEE is ${user.tdee}`);;
}

const myTdeeForm = document.getElementById("tdeeCalc")

myTdeeForm.addEventListener('submit', (e)=>{
    e.preventDefault();

    const tdeeFormData = new FormData(myTdeeForm);

  const user = Object.fromEntries(tdeeFormData.entries())

   tdeeResult(user);

});

const poundsConversion = function (weight) {
  weight = Number(weight)
  return weight / 2.2046
}

const inchesConversion = function (height) {
  height = Number(height)
  return height * 2.54
}


const maleTdee = function (user){
  return 66   (13.7 * user.weight)   (5 * user.height) - (6.8 * Number(user.height));
}

const femaleTdee = function (user){
  return 655   (9.6 * user.weight)   (1.8 * user.height) - (4.7 * Number(user.height));
}

The fixes were: remove the first initialization of the "user" constant, receive the "user" parameter in "tdeeResult" function, move the if statements for weight and height inside the same function, wrap some values obtained in the form that They were used with mathematical operators since despite clarifying that the input is of type number, in javascript they are received as strings, making the "poundsConversion" and "inchesConversion" functions work with parameters.

I highly recommend you learn in depth about scope in javascript, I hope my answer helps you.

  • Related