How can I create a function that adds the values ​​assigned to buttons?
P粉231112437
P粉231112437 2024-04-02 21:26:24
0
2
582

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粉231112437
P粉231112437

reply all(2)
P粉409742142

PIZZA SUPREME

Select a crust and toppings to build your own pizza!

Crust

$10 per crust.

Total:

0
P粉649990163

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:

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template