0

How do you use javascript to isolate all of the checked items on the html file.
I want to see what is checked, this tells me what items are selected from a menu.
A menu has prices for the items checked.
How do you access those items checked in the javascript array that has the price.
I then want to sum up the price for all of the items checked on the html menu.
Almost got a code. I want to use a forEach(), then isolate the item checked with it s id.
I thought about using split('Checkbox'). But, I am scratching my head then, how you get that to work to get the menuItem array price to add and get total. total += menu.price.

var menuItems = 
  [ { itemName: 'salad',        price: 13.95 } 
  , { itemName: 'pancakes',     price:  8.95 } 
  , { itemName: 'omlette',      price:  8.95 } 
  , { itemName: 'croissant',    price:  5.95 } 
  , { itemName: 'muffin',       price:  8.95 } 
  , { itemName: 'cheeseburger', price: 10.95 } 
  , { itemName: 'teriyaki',     price: 12.95 } 
  , { itemName: 'soup',         price: 11.95 } 
  , { itemName: 'coffee',       price:  1.95 } 
  , { itemName: 'tea',          price: 11.95 } 
  , { itemName: 'beer',         price:  5.95 } 
  , { itemName: 'milk',         price:  3.95 } 
  ] 
var total = 0;

document.querySelectorAll("input[type='checkbox']")
  .forEach(checkbox => {
    checkbox.addEventListener('click', function(event) { 
    if (event.target.checked) {
      console.log(event.target.checked);
      console.log('total ' + total);
    }   
  })         
});
<!DOCTYPE html>
<html xmlns:th="http://thymeleaf.org">
<head>
<title>MENU</title>
<script type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="css/menu.css" >
</head>
<body>

<div class="name">
  <h1>JOE'S FAMILY DINER</h1>
</div>

<table style="width:100%">
  <tr>
    <th>BreakFast</th>
    <th>Lunch</th> 
    <th>Beverages</th>
  </tr>
  <tr>
    <td>
      <label for="Pancakes"> <b>Blueberry Pancakes</b> </label>
      <input type="checkbox" id="panCheckbox" name="pancakes"/>
      $8.95
    </td>
    <td>
      <label for="burger"> <b>Cheeseburger</b> </label>
      <input type="checkbox" id="burg" name="burger"/>
      $10.95
    </td>
    <td>
      <label for="Coffee"> <b>Black Coffee:</b> </label>
      <input type="checkbox" id="cofCheckbox" name="coffee" />
      $1.95
    </td>
  </tr>
  <tr>
    <td>
      <label for="Omelette"><b>Vegetable Omelette</b></label>
      <input type="checkbox" id="omlCheckbox"  name="omlette"/>
      $8.95
    </td>
    <td>
      <label for="Wrap"> <b>Teriyaki Wrap:</b></label>
      <input type="checkbox" id="rapCheckbox" name="wrap" />
      $12.95
    </td>
    <td>
      <label for="Tea"><b>Green Tea:</b></label>
      <input type="checkbox"id="teCheckbox"  name="tea" />
      $11.95
    </td>
  </tr>
  <tr>
    <td>
      <label for="Croissant"> <b>Croissant:</b> </label>
      <input type="checkbox" id="crosCheckbox" name="croissant"/>
      $5.95
    </td>
    <td>
      <label for="salad"> <b>Ceasar Salad:</b> </label>
      <input type="checkbox" id="salCheckbox" name="sald" />
      $13.95
    </td>
    <td>
      <label for="beer"> <b>Corona Beer 12 oz:</b> </label>
      <input type="checkbox" id="BerCheckbox" name="Beer" />
      $5.95
    </td>
  </tr>
  <tr>
    <td> 
      <label for="Muffin"><b>Blueberry Muffin</b> </label>
      <input type="checkbox" id="MufCheckbox"  name="muffin"/>
      $8.95
    </td>
    <td>
      <label for="soup"> <b>Tomato Soup:</b> </label>
      <input type="checkbox" id="souCheckbox" name="soup" />
      $11.95
    </td>
    <td>
      <label for="Milk"> <b>Chocolate Milk:</b> </label>
      <input type="checkbox" id="milCheckbox" name="milk" />
      $3.95
    </td>
  </tr>
</table>
<div>
  <form>
    <input type="submit" value="Submit" id="sub">
    <input type="reset" value="Reset">
  </form>
</div>  
<div style="margin-top: 10px;">
  <button type="button">Total Amount</button>
</div>
        
<script type="text/javascript" src="/js/menu.js"></script>
</body>
</html>
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
  • do you want this on click of submit button or on click of total button or on check/uncheck of checkbox. – Amit Verma Jul 04 '21 at 02:10
  • have look to https://stackoverflow.com/questions/68194437/how-to-show-css-animation-in-form-with-javascript-validation-only-when-input-is/68195398#68195398 – Mister Jojo Jul 04 '21 at 02:25

3 Answers3

0

Something like this by specifying the price on the checkbox with a data attribute. Watch out for floating point errors though.

document.getElementById("SubmitButton").addEventListener('click', function(e) {
  e.preventDefault();
  var selectedItems = document.querySelectorAll('.item-selection:checked');
  
  var selectedItemPrices = [];
  var total = 0;
  
  for (var i = 0; i < selectedItems.length; i++) {
    var price = Number.parseFloat(selectedItems[i].getAttribute('data-price'));
  
    selectedItemPrices.push({
      itemName: selectedItems[i].getAttribute('name'),
      price: price.toFixed(2)
    });
    
    total += price;
  }
  
  console.log(selectedItemPrices);
  console.log(total.toFixed(2));
});
<table style="width:100%">
  <tr>
    <th>BreakFast</th>
    <th>Lunch</th>
    <th>Beverages</th>
  </tr>
  <tr>
    <td><label for="Pancakes"><b>Blueberry Pancakes</b></label>
      <input class="item-selection" type="checkbox" id="panCheckbox" name="pancakes" data-price="8.95" />$8.95</td>
    <td><label for="burger"><b>Cheeseburger</b></label>
      <input class="item-selection" type="checkbox" id="burg" name="burger" data-price="10.95"/>$10.95</td>
    <td><label for="Coffee"><b>Black Coffee:</b></label>
      <input class="item-selection" type="checkbox" id="cofCheckbox" name="coffee" data-price="1.95"/>$1.95</td>
  </tr>
  <tr>
    <td><label for="Omelette"><b>Vegetable Omelette</b></label>
      <input class="item-selection" type="checkbox" id="omlCheckbox" name="omlette" data-price="8.95"/>$8.95</td>
    <td><label for="Wrap"><b>Teriyaki Wrap:</b></label>
      <input class="item-selection" type="checkbox" id="rapCheckbox" name="wrap" data-price="12.95"/>$12.95</td>
    <td><label for="Tea"><b>Green Tea:</b></label>
      <input class="item-selection" type="checkbox" id="teCheckbox" name="tea" data-price="11.95"/>$11.95</td>
  </tr>
  <tr>
    <td> <label for="Croissant"><b>Croissant:</b></label>
      <input class="item-selection" type="checkbox" id="crosCheckbox" name="croissant" data-price="5.95"/>$5.95</td>
    <td><label for="salad"><b>Ceasar Salad:</b></label>
      <input class="item-selection" type="checkbox" id="salCheckbox" name="sald" data-price="13.95"/>$13.95</td>
    <td><label for="beer"><b>Corona Beer 12 oz:</b></label>
      <input class="item-selection" type="checkbox" id="BerCheckbox" name="Beer" data-price="5.95"/>$5.95</td>
  </tr>
  <tr>
    <td> <label for="Muffin"><b>Blueberry Muffin</b></label>
      <input class="item-selection" type="checkbox" id="MufCheckbox" name="muffin" data-price="8.95"/>$8.95</td>
    <td><label for="soup"><b>Tomato Soup:</b></label>
      <input class="item-selection" type="checkbox" id="souCheckbox" name="soup" data-price="11.95"/>$11.95</td>
    <td><label for="Milk"><b>Chocolate Milk:</b></label>
      <input class="item-selection" type="checkbox" id="milCheckbox" name="milk" data-price="3.95"/>$3.95</td>
  </tr>
</table>
<div>
  <form>
    <input id="SubmitButton" type="submit" value="Submit" id="sub">
    <input type="reset" value="Reset">
  </form>
</div>
<div style="margin-top: 10px;">
  <button type="button">Total Amount</button>
</div>
brice
  • 1,801
  • 1
  • 10
  • 15
0

Try this. This solution will on check/uncheck of check box. I you need this on any button click, let me know I will modify.

I have modified your HTML also. You can use value attribute of check box and assign item value there. In JavaScript it can be used for further calculation. Let me know if there is any issue.

<!DOCTYPE html>
<html xmlns:th="http://thymeleaf.org">
<head>
    <title>MENU</title>
    <script type="text/javascript" src="/js/menu.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript">

        var total = 0;
        $(document).ready(function () {
            $('input[type="checkbox"]').change(function () {
                var ischecked = $(this).is(':checked');
                if (!ischecked) {
                    total -= parseFloat($(this).val());
                } else {
                    total += parseFloat($(this).val());
                }
                console.log(total.toFixed(2));
            });
        });

    </script>
    <link rel="stylesheet" type="text/css" href="css/menu.css">
</head>
<body>
    <form>
        <div class="name">
            <h1>JOE'S FAMILY DINER</h1>
        </div>

        <table style="width:100%">
            <tr>
                <th>BreakFast</th>
                <th>Lunch</th>
                <th>Beverages</th>
            </tr>
            <tr>
                <td>
                    <label for="Pancakes"> <b>Blueberry Pancakes</b> </label>
                    <input type="checkbox" id="panCheckbox" name="pancakes" value="8.95" />$8.95

                </td>
                <td>
                    <label for="burger"> <b>Cheeseburger</b> </label>
                    <input type="checkbox" id="burg" name="burger" value="10.95" />
                    $10.95
                </td>
                <td>
                    <label for="Coffee"> <b>Black Coffee:</b> </label>
                    <input type="checkbox" id="cofCheckbox" name="coffee" value="1.95" />
                    $1.95
                </td>
            </tr>
            <tr>
                <td>
                    <label for="Omelette"><b>Vegetable Omelette</b></label>
                    <input type="checkbox" id="omlCheckbox" name="omlette" value="8.95" />
                    $8.95
                </td>
                <td>
                    <label for="Wrap"> <b>Teriyaki Wrap:</b></label>
                    <input type="checkbox" id="rapCheckbox" name="wrap" value="12.95" />
                    $12.95
                </td>
                <td>
                    <label for="Tea"><b>Green Tea:</b></label>
                    <input type="checkbox" id="teCheckbox" name="tea" value="11.95" />
                    $11.95
                </td>
            </tr>
            <tr>
                <td>
                    <label for="Croissant"> <b>Croissant:</b> </label>
                    <input type="checkbox" id="crosCheckbox" name="croissant" value="5.95" />
                    $5.95
                </td>
                <td>
                    <label for="salad"> <b>Ceasar Salad:</b> </label>
                    <input type="checkbox" id="salCheckbox" name="sald" value="13.95" />
                    $13.95
                </td>
                <td>
                    <label for="beer"> <b>Corona Beer 12 oz:</b> </label>
                    <input type="checkbox" id="BerCheckbox" name="Beer" value="5.95" />
                    $5.95
                </td>
            </tr>
            <tr>
                <td>
                    <label for="Muffin"><b>Blueberry Muffin</b> </label>
                    <input type="checkbox" id="MufCheckbox" name="muffin" value="8.95" />
                    $8.95
                </td>
                <td>
                    <label for="soup"> <b>Tomato Soup:</b> </label>
                    <input type="checkbox" id="souCheckbox" name="soup" value="11.95" />
                    $11.95
                </td>
                <td>
                    <label for="Milk"> <b>Chocolate Milk:</b> </label>
                    <input type="checkbox" id="milCheckbox" name="milk" value="3.95" />
                    $3.95
                </td>
            </tr>
        </table>
        <div>
            <input type="submit" value="Submit" id="sub">
            <input type="reset" value="Reset">
        </div>
        <div style="margin-top: 10px;">
            <button type="button">Total Amount</button>
        </div>
    </form>
</body>
</html>
Amit Verma
  • 2,450
  • 2
  • 8
  • 21
0

the simplest way is to use FormData It get only the checked elements in a form.

which also means that your html must be rearranged for this job

since the answers proposed here have for the moment been completely overlooked on how to use the forms here is what I will find as an acceptable answer

const menuItems = 
  { BreakFast :
    [ { itemName: 'pancakes',  price: 8.95, label: 'Blueberry Pancakes' }
    , { itemName: 'omlette',   price: 8.95, label: 'Vegetable Omelette' }
    , { itemName: 'croissant', price: 5.95, label: 'Croissant'          }
    , { itemName: 'muffin',    price: 8.95, label: 'Blueberry Muffin'   }
    ]
  , Lunch :
    [ { itemName: 'cheeseburger', price: 10.95, label: 'Cheeseburger'  }
    , { itemName: 'teriyaki',     price: 12.95, label: 'Teriyaki Wrap' }
    , { itemName: 'salad',        price: 13.95, label: 'Ceasar Salad'  }
    , { itemName: 'soup',         price: 11.95, label: 'Tomato Soup'   }
    ]
  , Beverages :
    [ { itemName: 'coffee', price:  1.95, label: 'Black Coffee'      }
    , { itemName: 'tea',    price: 11.95, label: 'Green Tea'         }
    , { itemName: 'beer',   price:  5.95, label: 'Corona Beer 12 oz' }
    , { itemName: 'milk',   price:  3.95, label: 'Chocolate Milk'    }
    ]
  }

const
  myForm = document.querySelector('#my-form-id')
, total  = document.querySelector('#total > em')

for (let menu in menuItems) // build the menu
  {
  let menuPart = document.createElement('fieldset') 
  menuPart.innerHTML = `<legend>${menu}</legend>`
  menuItems[menu].forEach(item=>
    {
    menuPart.innerHTML += `
        <label>
          <b>${item.label}</b>
          <input type="checkbox" name="${item.itemName}" value="${item.price}">
          <em>$ ${item.price}</em>
        </label>`
    })
  myForm.querySelector('.cols-3-parts').appendChild(menuPart)
  }
myForm.onsubmit = e =>
  {
  e.preventDefault() // disable submit while testing

  let inputJSON = Array.from(new FormData(myForm))
    .reduce((r,[name,value])=>{ r[name]= isNaN(value) ? value : Number(value); return r} ,{}) 
  console.log( JSON.stringify( inputJSON ))
  setTimeout(console.clear, 2000);
  }
myForm.onreset = e =>
  {
  total.textContent = '0.00'
  }
myForm.oninput = e =>
  {
  let  totalVal = 0;
  Array.from(new FormData(myForm))
    .forEach(([name,value])=> totalVal += isNaN(value) ? 0 : Number(value) ) 
    
  total.textContent = totalVal.toFixed(2)
  }
form#my-form-id {
  width   : 60em;
  padding : .4em;
  }
button {
  margin : 1em .4em 0 0;
  width  : 6em;
  }
.cols-3-parts {
  display   : flex;
  flex-wrap : wrap;
  }
.cols-3-parts fieldset {
  flex-grow : 1;
  width     : 30%;
  }
.cols-3-parts fieldset label {
  display : block;
  float   : left;
  clear   : left; 
  }
.cols-3-parts fieldset label b {
  display       : inline-block;
  width         : 11.4em;
  text-overflow : "";
  white-space   : nowrap;
  overflow      : hidden;
  }
.cols-3-parts fieldset label b::after {
  content     : '...............................';
  color       : grey;
  font-weight : normal;
  }
.cols-3-parts fieldset label input[type="checkbox"] {
  vertical-align: top;
  }
.cols-3-parts fieldset label em {
  font-size      : .8em;
  vertical-align : top;
  }
<h1>JOE'S FAMILY DINER</h1>

<form action="xx" id="my-form-id">
  <div class='cols-3-parts'> </div>

  <button type="submit">Submit</button>
  <button type="reset" >Reset</button>
</form>

<p id="total">
  Total : $ <em>0.00</em>
</p>
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40