Home  >  Q&A  >  body text

How can I create a function that adds the values ​​assigned to buttons?

New coder here. I'm creating a pizza menu application that adds up the values ​​assigned to the top buttons and displays them in a "Total" at the bottom of the list. But I'm having trouble getting the code to show the cost when adding ingredients.

Here's what I tried:

let whiteWheat = document.getElementById("white-wheat");
let multiGrain = document.getElementById("multi-grain");
let caulifl = document.getElementById("cauliflower");
let thinCrust = document.getElementById("thin-crust");
let deepDish = document.getElementById("deep-dish");
let totalField = document.getElementById("total");
totalField = 0;

whiteWheat.addEventListener(click, function() {
  var totalCost = totalField + 10;
  var finalOrder = document.createElement("li");
  finalOrder.innerText = totalCost.value;
  totalField.appendChild(finalOrder);
});
<h1>PIZZA SUPREME</h1>
<h2>Select a crust and toppings to build your own pizza!</h2>
<h3>Crust</h3>
<h4> per crust.</h4>
<ul><button id="white-wheat">white wheat</button></ul>
<ul><button id="multi-grain">multigrain</button></ul>
<ul><button id="cauliflower">Cauliflower</button></ul>
<ul><button id="thin-crust">Thin Crust</button></ul>
<ul><button id="deep-dish">Deep Dish</button></ul>

<h2>Total:</h2>
<div id="total">
</div>

P粉231112437P粉231112437183 days ago434

reply all(2)I'll reply

  • P粉409742142

    P粉4097421422024-04-03 18:37:03

    PIZZA SUPREME

    Select a crust and toppings to build your own pizza!

    Crust

    $10 per crust.

    Total:

    0

    reply
    0
  • P粉649990163

    P粉6499901632024-04-03 16:49:54

    A better approach might be to create x-price properties on the buttons and put them inside

    . This way you can add the value of the x-price property using a single event listener and event propagation. like this:

    let totalPrice = 0;
    const totalDiv = document.getElementById('total');
    const itemsDiv = document.getElementById('items');
    
    document.getElementById('buttons').addEventListener('click', e => {
      totalPrice += parseFloat(e.target.getAttribute('x-price'));
      totalDiv.textContent = totalPrice;
      
      const li = document.createElement('li');
      li.textContent = e.target.textContent;
      itemsDiv.appendChild(li);
    });

    PIZZA SUPREME

    Select a crust and toppings to build your own pizza!

    Crust

    Total:

    reply
    0
  • Cancelreply