I want to make a shopping cart and update the total every time I add a product, all the products cost 100 pesos, the function code is the following, and the result is that the console only leaves 100 and before that the number of times I clicked add to cart
function enviarProducto(pro){
const div = document.createElement('div');
div.innerHTML = `
<div class="row mb-3">
<div class="col-3">
<img src="${pro.imagen}" class="imagen-producto-carrito">
<div class="row">
<div class ="col ml-4"><h4 class="titulo-producto-carrito">${pro.titulo}</h4></div>
</div>
</div>
<div class="col-9">
<h4>Precio: <span class="precio-producto-carrito text-aling-center">${pro.precio}</span></h4>
<div class="row">
<div class ="col"><p class="texto-producto-carrito">${pro.descripcion}</p></div>
</div>
<div class="row">
<div class ="col"><button id="${pro.id}" class="boton-eliminar-carrito btn btn-danger btn-block">Eliminar del carrito</button></div>
</div>
</div>
</div>
`;
body.appendChild(div);
guardarProductoLS(pro);
let total = 0;
let precio = parseInt(pro.precio);
total = precio + total;
console.log(total);
}
It's not adding the values because every time you see that you call the function
enviarProducto
you're setting the variabletotal
to 0.What you should do is move the variable
total
outside of the function, for example like this: