how to fix javascript

when the checkbox is checked by the user, I want to push the value(the numerical value are in the JS) for the checked box in an array, get the sum and display the total calories in the alert message.

here's my code so far:

var rice = 204;
var bread = 140;
var chicken = 147;
var beef = 282;
var carrots = 150;
var beans = 70;

function myFunction() {
  var rice = document.getElementById("rice");
  var bread = document.getElementById("bread");
  var chicken = document.getElementById("chicken");
  var beef = document.getElementById("beef");
  var carrots = document.getElementById("carrots");
  var beans = document.getElementById("beans");

  const food = [];

  if (rice.checked == true) {
    food.push(window.rice);
  } else if (bread.checked == true) {
    food.push(window.bread);
  } else if (chicken.checked == true) {
    food.push(window.chicken);
  } else if (beef.checked == true) {
    food.push(window.beef);
  } else if (carrots.checked == true) {
    food.push(window.carrots);
  } else if (beans.checked == true) {
    food.push(window.beans);
  }

  let sum = food.reduce(function(a, b) {
    return a + b;
  }, 0);

  console.log(sum); /*sum of array not working */
  console.log(food);

}

myFunction();
<form>
  <h2>Meal Plan</h2>

  <h3>Dietary restrictions:</h3>

  <input type="radio" name="diet" id="none" value="none" required>
  <label for="none">None</label>
  <br/><input type="radio" name="diet" id="vegetarian" value="vegetarian" required>
  <label for="vegetarian">Vegetarian</label>
  <br/><input type="radio" name="diet" id="lowcarb" value="lowcarb" required>
  <label for="lowcarb">Low Carb</label>

  <br />

  <h3>Food items:</h3>
  <input type="checkbox" name="Rice" id="rice" value="rice">
  <label for="rice">Rice</label>
  <br /><input type="checkbox" name="Beef" id="beef" value="beef">
  <label for="beef">Beef</label>
  <br /><input type="checkbox" name="Bread" id="bread" value="bread">
  <label for="bread">Bread</label>
  <br /><input type="checkbox" name="Beans" id="beans" value="beans">
  <label for="beans">Beans</label>
  <br /><input type="checkbox" name="Chicken" id="chicken" value="chicken">
  <label for="chicken">Chicken</label>
  <br /><input type="checkbox" name="Carrots" id="carrots" value="carrots">
  <label for="carrots">Carrots</label>

  <br /><br /><input type="submit" onclick="myFunction()" />
</form>
<script src="try.js"></script>

the values is not appending in the array when i check multuple boxes. it only appends the first box that i checked and doesn't include the next boxes. i cant get the sum, how can i fix that?

Upvotes: -1

Views: 218

Answers (2)

Mister Jojo
Mister Jojo

Reputation: 22422

do that this way ... (less code and more readability)

const
  myForm = document.forms['my-form']
, calories = 
  { rice    : 204
  , bread   : 140
  , chicken : 147
  , beef    : 282
  , carrots : 150
  , beans   :  70
  }
, NotVegetarianFood =  ['beef', 'chicken' ]
  ;
myForm.oninput = e =>
  {
  if ( e.target.name === 'diet' ) 
    {
    let isVegetarian =  (myForm.diet.value === 'vegetarian')
    NotVegetarianFood.forEach( food =>
      {
      myForm[food].disabled = isVegetarian
      if (isVegetarian) 
        myForm[food].checked = false
      })
    }
  }
myForm.onsubmit = e =>
  {
  e.preventDefault()
  let 
    sum        = 0 
  , vegetables = 0
  , formValues = 
      Array
      .from(new FormData(myForm).entries() )
      .reduce((res,[food,_])=>
        {  
        if (!!calories[food]) 
          {
          vegetables += NotVegetarianFood.includes(food) ? 0 : 1
          sum        += calories[food] 
          res.push (food)
          }
        return res
        },[])

  myForm.message.textContent = (vegetables > 2) 
                             ? '' 
                             : '2 vegetables options are recommended for a healthy meal regardless of the dietary restrictions.'
  console.clear()
  console.log( JSON.stringify( formValues), '\n-- calories sum =', sum )
  }
fieldset {
  width         : 16em;
  margin-bottom : .7em;
  }
legend {
  font-weight : bold;
  }
label {
  display    : block;
  margin-top : .4em;
  }
<form name="my-form">
  <h3>Meal Plan</h3>
  <fieldset>
    <legend>Dietary restrictions:</legend>
    <label> <input type="radio" name="diet" value="none" checked > None       </label>  
    <label> <input type="radio" name="diet" value="vegetarian"   > vegetarian </label>  
    <label> <input type="radio" name="diet" value="lowcarb"      > Low Carb   </label>  
  </fieldset>
  <fieldset>
    <legend>Food items:</legend>
    <label> <input type="checkbox" name="rice"    > Rice    </label>  
    <label> <input type="checkbox" name="beef"    > Beef    </label>  
    <label> <input type="checkbox" name="bread"   > Bread   </label>  
    <label> <input type="checkbox" name="beans"   > Beans   </label>  
    <label> <input type="checkbox" name="chicken" > Chicken </label>  
    <label> <input type="checkbox" name="carrots" > Carrots </label>  
  </fieldset>
  
  <button type="submit">submit</button>

  <output name="message"></output>
</form>

Upvotes: 0

ProDec
ProDec

Reputation: 5420

You can do this way

document.querySelector('form').addEventListener('click', e => {
  if (e.target.matches('input[type="radio"]')) {
    const checked = document.querySelector('#vegetarian').checked;
    document.querySelectorAll('.meat').forEach(chk => {
      chk.disabled = checked;
      chk.checked = false;
    });
  }
});

const calories = {
 rice: 204,
 bread: 140,
 chicken: 147,
 beef: 282,
 carrots: 150,
 beans: 70
};

function myFunction() {
    
    const food = [];
    const veg = [];
    let sum = 0;

    document.querySelectorAll('input[type="checkbox"]').forEach(chk => {
      if (chk.checked) {
        food.push(chk.value);
        if (chk.classList.contains('veg')) {
          veg.push(chk.value);
        }
        sum += (calories[chk.value] || 0);
      }
    });

    console.log(sum); /*sum of array not working */
    alert(food);
    if (veg.length < 2) {
      alert('two vegs are recommendeded');
    }

}
<!DOCTYPE html>
<html>
    <head>
        <title>Meal Plan</title>
    </head>
    <body>
        <form onsubmit="return false;">
            <h2>Meal Plan</h2>

            <h3>Dietary restrictions:</h3>

            <input type="radio" name="diet" id="none" value="none" required>
            <label for="none">None</label>
            <br/><input type="radio" name="diet" id="vegetarian" value="vegetarian" required>
            <label for="vegetarian">Vegetarian</label>
            <br/><input type="radio" name="diet" id="lowcarb" value="lowcarb" required>
            <label for="lowcarb">Low Carb</label>

            <br />

            <h3>Food items:</h3>
            <input type="checkbox" name="Rice" id="rice" value="rice">
            <label for="rice">Rice</label>
            <br /><input type="checkbox" name="Beef" class="meat" id="beef" value="beef">
            <label for="beef">Beef</label>
            <br /><input type="checkbox" name="Bread" id="bread" value="bread">
            <label for="bread">Bread</label>
            <br /><input type="checkbox" name="Beans" class="veg" id="beans" value="beans">
            <label for="beans">Beans</label>
            <br /><input type="checkbox" name="Chicken" class="meat" id="chicken" value="chicken">
            <label for="chicken">Chicken</label>
            <br /><input type="checkbox" name="Carrots" class="veg" id="carrots" value="carrots">
            <label for="carrots">Carrots</label>

            <br /><br /><input type="submit" onclick="myFunction()" />
        </form>
    </body>
</html>

Your existing if ... else if ... block got problem, it won't run the rest of else if once a condition is true.

Upvotes: 2

Related Questions