i am making a menu calculator that gives you the total of the products, but im stuck cause i don't know where to start,
i was thinking to use if else statement and put multiple id's on every button and somehow calculate the total but i think is very inefficient so if someone have a better idea, it would be perfect
!! oh by the way !! im generating the buttons elements with create-element and appendchild .
here is my code
////////////////////HTML//////////////////////////
<body>
<div id="container">
</div>
<div >
<p>price</p>
<p>total</p>
</div>
</body>
</html>
/////////////////Javascript//////////////////////////
nombres = ['Kg','Taco','Dorado','1LtCSM','1/2CSM','Boing','Cafe','Refresco'];
precios = [440,30,24,50,25,20,20,25];
Total = [];
const element = document.querySelector('.icons-container');
for(i=0;i<=7;i ){
let div = document.createElement('div');
let h3 = document.createElement('h3');
div.classList.add('cuadro');
div.appendChild(h3);
h3.textContent = `${nombres[i]}`;
h3.classList.add('icon-text');
element.appendChild(div);
};
i haven't tried nothing but i was thinking to use if else and add different id's on every button to differentiate each one,
CodePudding user response:
by using an array of objects, and a .forEach()
loop, we solve all your problems, in a simpler way.
with this solution, there isn't any need to add or
id=""
to every button because we used a simple concept called Closures
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures which makes .forEach()
and .addEventListener()
together work very fine here!
const menuData = [{
name: "Kg",
price: 440,
},
{
name: "Taco",
price: 30,
},
{
name: "Dorado",
price: 24,
},
{
name: "1LtCSM",
price: 50,
},
{
name: "1/2CSM",
price: 25,
},
{
name: "Boing",
price: 20,
},
{
name: "Cafe",
price: 20,
},
{
name: "Refresco",
price: 25,
},
];
generateGrid(menuData, document.querySelector(".icons-container"));
function generateGrid(menuData, parent) {
let total = 0;
menuData.forEach((menuItem) => {
const btn = document.createElement("button");
const h3 = document.createElement("h3");
btn.appendChild(h3);
parent.appendChild(btn);
h3.textContent = menuItem.name;
btn.addEventListener("click", () => {
const priceEl = document.getElementById("price");
const totalEl = document.getElementById("total");
total = menuItem.price;
priceEl.textContent = menuItem.price;
totalEl.textContent = total;
});
});
}
/* use your own css here, this is just for demo purposes */
body,
.icons-container {
gap: 0.5rem;
}
.icons-container,
.displayer {
display: grid;
grid-auto-flow: column;
grid-auto-columns: 1fr;
}
.displayer>div {
text-align: center;
}
.displayer div>div {
font-size: 200%;
font-weight: bold;
}
<div >
<!-- JS will put the divs here -->
</div>
<div >
<div>
<p>price</p>
<div id="price">0</div>
</div>
<div>
<p>total</p>
<div id="total">0</div>
</div>
</div>