On my page I have several products, each one with its respective add to cart button, when that button is clicked a box opens with a list of the products that are being added where it says their name, quantity and price . The problem is that if I add the same product again it is repeated in the list
and instead of that I want the quantity to increase, that is, if before it said "product x, quantity 1" I want it to say "product x quantity 2" but not to repeat it. So I need a method, a conditional to detect if a product is already added to my list
Here some code:
let lista_de_productos = document.querySelector(".lista_de_productos");
carrito_btn = document.querySelectorAll(".btn_carrito");
for (cada_btn_carrito of carrito_btn) {
let precio_c = cada_btn_carrito.parentElement.parentElement.querySelector("p").innerHTML;
let nombre_c = cada_btn_carrito.parentElement.parentElement.querySelector("h3 a").innerHTML;
cada_btn_carrito.onclick = () => {
lista_de_productos.innerHTML +=
` <li>
<div class='nombre_p_list w-50'>${nombre_c}</div>
<input type='text' name='' value='1'>
<span class='mx-3 cerrar_lista'>x</span>
<span class='list_price'>${precio_c}</span>
</li> `
}
}
<!-- el producto ----->
<article class="producto">
<a href="http://"><img src="img/miProducto.jpg"></a>
<h3><a href="http://">titulo de mi producto</a></h3>
<p class="precio">$325.00</p>
<i class="btn_carrito">mi boton carrito</i>
</article>
<!-- la lista ----------->
<form class="lista_carrito">
<div class="text-right">
<span class="">x</span>
</div>
<ul class=" lista_de_productos list-unstyled border mx-2">
<!-- aqui agrego las listas con javascript -->
</ul>
</form>
I see that you directly collect the name, the price and place it in the cart list, it would be better if you keep all the products that the customer chooses in an arrangement and that each element had an ID so that with a conditional you could know if the item is repeated element and to that element only add the price of the product.
Here is an example of how you could do it: I have published it in codepen so you can understand it better* https://codepen.io/tekendaniel/pen/xvVqdZ