Addition and Subtraction buttons won`t work after list in list (JavaScript)

Viewed 73

I recently started a project o add items to tables in a restaurant and save the value.

I started with one Item list and it worked perfectly fine but as soon as I added a second list and tried subtracting/adding items via buttons the amount of items would go down/up but the sum would stay the same.

The Sum still updates when adding new items though.

If added the code below you can execute it like that and test yourself.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Prototyp</title>
    <style>
        .table{
        text-align: center;
        line-height: 9vh;
        height: 10vh;
        }

        .tablei{
        background-color: #e58e26;
        font-size: 44pt;
        }

        .table-down{
        margin-top: 90vh;
        }

        .left, .right{
            width: 45vw;
            height: 100vh;
            border: solid 1pt black;
            display: table-cell;
            font-size: 20pt;
        }

        .wrapperBottom{
            display: none;
        }

        .btn{
        background-color: #e58e26 !important;
        }

        .btn-right{
        font-size: 28pt;
        margin-left: 15vh;
        color: #e58e26;
        }

        body{
        background-color: #292929;
        color: white;
        font-size: 16pt;
        font-weight: bold;
        }

    </style>


    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

</head>
<body onload="init()">
<div class="row" id="up">
    <div class="table tablei col s1" onclick="goNext(1)">1</div>
</div>




<div class="row wrapperBottom" id="bottom">
    <div class="col s5" id="sum"></div>
    <div class="col s2">
    <a class="waves-effect waves-light btn table-down" onclick="goBack()">back to table</a>
  </div>

    <div class="wrapperacordion">
    <button class="accordion accordionheadings">Softdrinks</button>
    <div class="col s5 accordionbabahaft" id="Softdrinks"></div>

    <button class="accordion accordionheadings">Juice</button>
    <div class="col s5 accordionbabahaft" id="Juice"></div>

    </div>

</div>

<script>
    let tables;
    let currentTable;
    let products;



    softdrinks = [
        {name:"Water", price:2.40},
        {name:"Soda", price:2.70},
    ]



    juice = [
        {name:"OrangeJuice", price:2.40},
        {name:"AppleJuice", price:3.90},
        {name:"BananaJuice", price:2.40}
    ]



    function init() {
        tables = [];
        products = [];
        products['Softdrinks'] = softdrinks;
        products['Juice'] = juice;
    }


    function goNext(tablenumber){
        currentTable = tablenumber;
        if(!tables[tablenumber]){
            tables[tablenumber] = {products: [], sum: 0};
        }
        document.getElementById("bottom").style.display = 'block';
        document.getElementById("up").style.display = 'none';

        document.getElementById("Softdrinks").innerHTML = "";
        document.getElementById("Juice").innerHTML = "";

        for (let list in products) {

          for (let prod of products[list]){

           let button = document.createElement("a");
           button.setAttribute('class', 'button accordionitems');
           button.onclick = () =>{
               let entry = null;
               for (let pos of  tables[tablenumber].products) {
                   if(pos.name === prod.name){
                       entry = pos;
                   }
               }
               if(!entry){
                   entry = {name:prod.name, amount: 0, price: 0}
                   tables[tablenumber].products.push(entry)
               }
               entry.amount++;
               entry.price+= prod.price;
               updateSum();
           }

            button.innerText = prod.name + " " + prod.price + "€";

            document.getElementById(list).append(button)
            updateSum();
        }

      }



    }

    function findPrice(name) {
        let price = 0;

        for(let prod of products){
            if(prod.name === name){
                price = prod.price;
                break;
            }
        }
        return price;
    }

    function updateSum(){
        document.getElementById("sum").innerHTML = "";
        let sum  = 0;
        let hr = document.createElement("hr");
        let sumDiv = document.createElement("div");
        let deleteButton = document.createElement("a");
        deleteButton.setAttribute('class', 'waves-effect waves-light btn');
        for (let prod of tables[currentTable].products) {
           let div = document.createElement("div");
            let label = document.createElement("span");
            label.innerHTML = prod.amount + "x " + prod.name +": "+ prod.price.toFixed(2) +"&euro;&nbsp;";
            sum += prod.price;

            let divPlusMinus = document.createElement("aside");
            div.appendChild(divPlusMinus);
            divPlusMinus.setAttribute('class', 'gorightpls');
            let plus = document.createElement("a");
            plus.setAttribute('class', 'btn-plus');
            plus.innerHTML ="+&nbsp;";
            plus.addEventListener("click", ()=>{
                prod.amount++;
                prod.price+= findPrice(prod.name);
                updateSum();
            });
            let minus = document.createElement("a");
            minus.setAttribute('class', 'btn-minus');
            minus.addEventListener("click", ()=>{
                prod.amount--;
                prod.price-= findPrice(prod.name);
                updateSum();

            });
            minus.innerHTML ="−&nbsp;";

            div.append(label);

            div.append(minus);

            divPlusMinus.append(plus);
            divPlusMinus.append(minus);

            document.getElementById("sum").append(div)


                  }

        tables[currentTable].sum  = sum;

        sumDiv.innerHTML = "Sum : "+sum.toFixed(2) +" &euro;"
        deleteButton.onclick = () =>{
            clicked();
        }
        deleteButton.innerText ="clear table"
        document.getElementById("sum").append(hr)
        document.getElementById("sum").append(sumDiv)
        document.getElementById("sum").append(deleteButton)
    }

    function goBack(){
        document.getElementById("bottom").style.display = 'none';
        document.getElementById("up").style.display = 'block';
    }


    function clicked() {
        var r = confirm("Wirklich löschen?");
        if(r==true){
            tables[currentTable].products = [];
            updateSum();
            goBack();
        } else {
        }
    }

    document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('select');
    var instances = M.FormSelect.init(elems);
    });


    var acc = document.getElementsByClassName("accordion");
    var i;

    for (i = 0; i < acc.length; i++) {
      acc[i].addEventListener("click", function() {

        this.classList.toggle("active");

        var panel = this.nextElementSibling;
        if (panel.style.display === "block") {
          panel.style.display = "none";
        } else {
          panel.style.display = "block";
        }
      });
    }


</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>
</html>

Thanks for helping

let tables;
let currentTable;
let products;



softdrinks = [{
    name: "Water",
    price: 2.40
  },
  {
    name: "Soda",
    price: 2.70
  },
]



juice = [{
    name: "OrangeJuice",
    price: 2.40
  },
  {
    name: "AppleJuice",
    price: 3.90
  },
  {
    name: "BananaJuice",
    price: 2.40
  }
]



function init() {
  tables = [];
  products = [];
  products['Softdrinks'] = softdrinks;
  products['Juice'] = juice;
}


function goNext(tablenumber) {
  currentTable = tablenumber;
  if (!tables[tablenumber]) {
    tables[tablenumber] = {
      products: [],
      sum: 0
    };
  }
  document.getElementById("bottom").style.display = 'block';
  document.getElementById("up").style.display = 'none';

  document.getElementById("Softdrinks").innerHTML = "";
  document.getElementById("Juice").innerHTML = "";

  for (let list in products) {

    for (let prod of products[list]) {

      let button = document.createElement("a");
      button.setAttribute('class', 'button accordionitems');
      button.onclick = () => {
        let entry = null;
        for (let pos of tables[tablenumber].products) {
          if (pos.name === prod.name) {
            entry = pos;
          }
        }
        if (!entry) {
          entry = {
            name: prod.name,
            amount: 0,
            price: 0
          }
          tables[tablenumber].products.push(entry)
        }
        entry.amount++;
        entry.price += prod.price;
        updateSum();
      }

      button.innerText = prod.name + " " + prod.price + "€";

      document.getElementById(list).append(button)
      updateSum();
    }

  }



}

function findPrice(name) {
  let price = 0;

  for (let prod of products) {
    if (prod.name === name) {
      price = prod.price;
      break;
    }
  }
  return price;
}

function updateSum() {
  document.getElementById("sum").innerHTML = "";
  let sum = 0;
  let hr = document.createElement("hr");
  let sumDiv = document.createElement("div");
  let deleteButton = document.createElement("a");
  deleteButton.setAttribute('class', 'waves-effect waves-light btn');
  for (let prod of tables[currentTable].products) {
    let div = document.createElement("div");
    let label = document.createElement("span");
    label.innerHTML = prod.amount + "x " + prod.name + ": " + prod.price.toFixed(2) + "&euro;&nbsp;";
    sum += prod.price;

    let divPlusMinus = document.createElement("aside");
    div.appendChild(divPlusMinus);
    divPlusMinus.setAttribute('class', 'gorightpls');
    let plus = document.createElement("a");
    plus.setAttribute('class', 'btn-plus');
    plus.innerHTML = "+&nbsp;";
    plus.addEventListener("click", () => {
      prod.amount++;
      prod.price += findPrice(prod.name);
      updateSum();
    });
    let minus = document.createElement("a");
    minus.setAttribute('class', 'btn-minus');
    minus.addEventListener("click", () => {
      prod.amount--;
      prod.price -= findPrice(prod.name);
      updateSum();

    });
    minus.innerHTML = "−&nbsp;";

    div.append(label);

    div.append(minus);

    divPlusMinus.append(plus);
    divPlusMinus.append(minus);

    document.getElementById("sum").append(div)


  }

  tables[currentTable].sum = sum;

  sumDiv.innerHTML = "Sum : " + sum.toFixed(2) + " &euro;"
  deleteButton.onclick = () => {
    clicked();
  }
  deleteButton.innerText = "clear table"
  document.getElementById("sum").append(hr)
  document.getElementById("sum").append(sumDiv)
  document.getElementById("sum").append(deleteButton)
}

function goBack() {
  document.getElementById("bottom").style.display = 'none';
  document.getElementById("up").style.display = 'block';
}


function clicked() {
  var r = confirm("Wirklich löschen?");
  if (r == true) {
    tables[currentTable].products = [];
    updateSum();
    goBack();
  } else {}
}

document.addEventListener('DOMContentLoaded', function() {
  var elems = document.querySelectorAll('select');
  var instances = M.FormSelect.init(elems);
});


var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {

    this.classList.toggle("active");

    var panel = this.nextElementSibling;
    if (panel.style.display === "block") {
      panel.style.display = "none";
    } else {
      panel.style.display = "block";
    }
  });
}
.table {
  text-align: center;
  line-height: 9vh;
  height: 10vh;
}

.tablei {
  background-color: #e58e26;
  font-size: 44pt;
}

.table-down {
  margin-top: 90vh;
}

.left,
.right {
  width: 45vw;
  height: 100vh;
  border: solid 1pt black;
  display: table-cell;
  font-size: 20pt;
}

.wrapperBottom {
  display: none;
}

.btn {
  background-color: #e58e26 !important;
}

.btn-right {
  font-size: 28pt;
  margin-left: 15vh;
  color: #e58e26;
}

body {
  background-color: #292929;
  color: white;
  font-size: 16pt;
  font-weight: bold;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Prototyp</title>
  <link rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
</head>

<body onload="init()">
  <div class="row" id="up">
    <div class="table tablei col s1" onclick="goNext(1)">1</div>
  </div>

  <div class="row wrapperBottom" id="bottom">
    <div class="col s5" id="sum"></div>
    <div class="col s2">
      <a class="waves-effect waves-light btn table-down" onclick="goBack()">back to table</a>
    </div>

    <div class="wrapperacordion">
      <button class="accordion accordionheadings">Softdrinks</button>
      <div class="col s5 accordionbabahaft" id="Softdrinks"></div>

      <button class="accordion accordionheadings">Juice</button>
      <div class="col s5 accordionbabahaft" id="Juice"></div>

    </div>

  </div>

  <script>
  </script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>

</html>

2 Answers

After adding categories, your 'products' array now has 2 named properties:

[Softdrinks: Array(2), Juice: Array(3)]

so when you are searching for price in findPrice(), you dont get products list in the first loop. You may:

function findPrice(name) {
    let price = 0;

    for(let category in products){
      for(let prod of products[category]){
          if(prod.name === name){
              price = prod.price;
              break;
          }
      }
    }

    return price;
}

Change iteration of products in findPrice().

products having first level of object then inside it list of values. You need two forloop to access this details.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Prototyp</title>
    <style>
        .table{
        text-align: center;
        line-height: 9vh;
        height: 10vh;
        }

        .tablei{
        background-color: #e58e26;
        font-size: 44pt;
        }

        .table-down{
        margin-top: 90vh;
        }

        .left, .right{
            width: 45vw;
            height: 100vh;
            border: solid 1pt black;
            display: table-cell;
            font-size: 20pt;
        }

        .wrapperBottom{
            display: none;
        }

        .btn{
        background-color: #e58e26 !important;
        }

        .btn-right{
        font-size: 28pt;
        margin-left: 15vh;
        color: #e58e26;
        }

        body{
        background-color: #292929;
        color: white;
        font-size: 16pt;
        font-weight: bold;
        }

    </style>


    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

</head>
<body onload="init()">
<div class="row" id="up">
    <div class="table tablei col s1" onclick="goNext(1)">1</div>
</div>




<div class="row wrapperBottom" id="bottom">
    <div class="col s5" id="sum"></div>
    <div class="col s2">
    <a class="waves-effect waves-light btn table-down" onclick="goBack()">back to table</a>
  </div>

    <div class="wrapperacordion">
    <button class="accordion accordionheadings">Softdrinks</button>
    <div class="col s5 accordionbabahaft" id="Softdrinks"></div>

    <button class="accordion accordionheadings">Juice</button>
    <div class="col s5 accordionbabahaft" id="Juice"></div>

    </div>

</div>

<script>
    let tables;
    let currentTable;
    let products;



    softdrinks = [
        {name:"Water", price:2.40},
        {name:"Soda", price:2.70},
    ]



    juice = [
        {name:"OrangeJuice", price:2.40},
        {name:"AppleJuice", price:3.90},
        {name:"BananaJuice", price:2.40}
    ]



    function init() {
        tables = [];
        products = [];
        products['Softdrinks'] = softdrinks;
        products['Juice'] = juice;
    }


    function goNext(tablenumber){
        currentTable = tablenumber;
        if(!tables[tablenumber]){
            tables[tablenumber] = {products: [], sum: 0};
        }
        document.getElementById("bottom").style.display = 'block';
        document.getElementById("up").style.display = 'none';

        document.getElementById("Softdrinks").innerHTML = "";
        document.getElementById("Juice").innerHTML = "";

        for (let list in products) {

          for (let prod of products[list]){

           let button = document.createElement("a");
           button.setAttribute('class', 'button accordionitems');
           button.onclick = () =>{ 
               let entry = null;
               for (let pos of  tables[tablenumber].products) {
                   if(pos.name === prod.name){
                       entry = pos;
                   }
               }
               if(!entry){
                   entry = {name:prod.name, amount: 0, price: 0}
                   tables[tablenumber].products.push(entry)
               }
               entry.amount++;
               entry.price+= prod.price;
               updateSum();
           }

            button.innerText = prod.name + " " + prod.price + "€";

            document.getElementById(list).append(button)
            updateSum();
        }

      }



    }

    function findPrice(name) {
        let price = 0;

        //console.log(products);
        //console.log(name);
        for (let prod of Object.values(products)) {

        //for(let prod of products){
           for(var i =0;i<prod.length; i ++){
            if(prod[i].name === name){
                price = prod[i].price;
         
                break;
            }
           }
        }
        return price;
    }

    function updateSum(){
        document.getElementById("sum").innerHTML = "";
        let sum  = 0;
        let hr = document.createElement("hr");
        let sumDiv = document.createElement("div");
        let deleteButton = document.createElement("a");
        deleteButton.setAttribute('class', 'waves-effect waves-light btn');
        for (let prod of tables[currentTable].products) {
           let div = document.createElement("div");
            let label = document.createElement("span");
            label.innerHTML = prod.amount + "x " + prod.name +": "+ prod.price.toFixed(2) +"&euro;&nbsp;";
            sum += prod.price;

            let divPlusMinus = document.createElement("aside");
            div.appendChild(divPlusMinus);
            divPlusMinus.setAttribute('class', 'gorightpls');
            let plus = document.createElement("a");
            plus.setAttribute('class', 'btn-plus');
            plus.innerHTML ="+&nbsp;";
            plus.addEventListener("click", ()=>{
            
                prod.amount++; 
                prod.price+= findPrice(prod.name);
                updateSum();
            });
            let minus = document.createElement("a");
            minus.setAttribute('class', 'btn-minus');

            minus.addEventListener("click", () => {
                prod.amount--;
                prod.price-= findPrice(prod.name);
                updateSum();
            });

            minus.innerHTML ="−&nbsp;";

            div.append(label);

            div.append(minus);

            divPlusMinus.append(plus);
            divPlusMinus.append(minus);

            document.getElementById("sum").append(div)


                  }

        tables[currentTable].sum  = sum;

        sumDiv.innerHTML = "Sum : "+sum.toFixed(2) +" &euro;"
        deleteButton.onclick = () =>{
            clicked();
        }
        deleteButton.innerText ="clear table"
        document.getElementById("sum").append(hr)
        document.getElementById("sum").append(sumDiv)
        document.getElementById("sum").append(deleteButton)
    }

    function goBack(){
        document.getElementById("bottom").style.display = 'none';
        document.getElementById("up").style.display = 'block';
    }


    function clicked() {
        var r = confirm("Wirklich löschen?");
        if(r==true){
            tables[currentTable].products = [];
            updateSum();
            goBack();
        } else {
        }
    }

    document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('select');
    var instances = M.FormSelect.init(elems);
    });


    var acc = document.getElementsByClassName("accordion");
    var i;

    for (i = 0; i < acc.length; i++) {
      acc[i].addEventListener("click", function() {

        this.classList.toggle("active");

        var panel = this.nextElementSibling;
        if (panel.style.display === "block") {
          panel.style.display = "none";
        } else {
          panel.style.display = "block";
        }
      });
    }


</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>
</html>

Related