Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

101
Visualizações
Cart products quantity not refreshing when clicked multiple times

When I click on a product i want the quantity to go up by 1 the function is working but is not showing in the cart unless I add another product that does not exist in the cart at that moment. Any help?

I tried but could not find the error. I think is the error is in the "if(existe){...}" but do not know where.

I edited it to add more code

const addToCart = document.querySelectorAll('.addToCart');
let carritoEl = document.querySelector('.ul');

let carrito = [];


 addToCart.forEach(btn => {
     btn.addEventListener('click', addToCarritoItem);});

 function addToCarritoItem(e){
     e.preventDefault();


     const boton = e.target;
     const item = boton.closest('.box'); 
    const itemTitle = item.querySelector('.producto-titulo').textContent;
    const itemPrice = item.querySelector('.precio').textContent;
    const itemImg = item.querySelector('.imgCart').src;
    const itemId = item.querySelector('.addToCart').getAttribute('data-id');
    

    const nuevoProducto = {

        title: itemTitle,
        price: itemPrice,
        image: itemImg,
        id: itemId,
        cantidad: 1

    };


    const existe = carrito.some(item => item.id === nuevoProducto.id); 

    console.log(existe);

    
    if(existe){

        const producto = carrito.map( item =>{
            if (item.id === nuevoProducto.id){
                item.cantidad++;
                return item;
            }else{
                return item;
            }
        });
    }else{
        addItemCarrito(nuevoProducto);
    }

 }

 function addItemCarrito(nuevoProducto){



    carritoSumaTotal();
    carrito.push(nuevoProducto);
    renderCarrito(); // 

 }

function renderCarrito(){
   // carritoEl.innerHTML = ""; //
    while(carritoEl.firstChild){
        carritoEl.removeChild(carritoEl.firstChild)
    };

    carrito.forEach((item) =>{

        carritoEl.innerHTML += `
        <li class="buyItem">
            <img src=${item.image}>
            <div class="productCartInfo">
                <h5 class="prdTitle">${item.title}</h5>
                <h6>${item.price}</h6>
                <div class="qnty">
                    <div>
                        <button class="mbtn">-</button>
                        <span class="countOfProduct">${item.cantidad}</span>
                        <button class="pbtn">+</button>
                    </div>
                    <div><i class="fas fa-times-circle dltProduct" data-id="${item.id}"></i></div>
                </div>
            </div>
        </li>
        `
    })


    carritoSumaTotal(); 
    
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

With no error logs or any demo, here is what I think: it is because you're not calling the renderCarrito function after you have incremented the quantity:

// Your Code
if(existe){
  const producto = carrito.map( item =>{
    if (item.id === nuevoProducto.id){
      item.cantidad++;
      return item;  // <--- Here you are just returning
    } else {
      return item;
    }
  }); // <--- You should probably call renderCarrito() after the mapping
} else {
  addItemCarrito(nuevoProducto);
}

Here is a snippet to help you understand what I am trying to explain:

if (existe) {
  // 1. map() would return an array
  //    Since you are updating the array contents, I would 
  //    suggest you use forEach() instead, like so:
  carrito.forEach(item => { 
    if (item.id === nuevoProducto.id) {
      item.cantidad++;
      // 2. No need to return item as this would update the item
      //    inside the carrito array directly
    }
    // 3. No need of 'else' block
    //    as you are incrementing only if the ids are same
  });
  
  // 4. Once you are done looping through
  //    you should probably invoke the renderCarrito() method here
  //    unless you want to do anything else
  renderCarrito();
} else {
  addItemCarrito(nuevoProducto);
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda