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

194
Visualizações
Cart delete an item and apply a coupon in js

I am trying to remove an item without removing the cart and reducing a price if the customer has a coupon or exceeds a certain quantity while js before using Django here is the html code js if you have any advice do not hesitate

html

            <div data-name="name" data-price="250" data-id="2">
                <img src="x.jpg" alt="" />
                <h3>name</h3>
                <input type="number" class="count" value="1" />
                <button class="tiny">Add to cart</button>
            </div>

<script type="text/template" id="cartT">
    <% _.each(items, function (item) { %> <div class = "panel"> <h3> <%= item.name %> </h3>  <span class="label">
    <%= item.count %> piece<% if(item.count > 1)
    {%>s
    <%}%> for <%= item.total %>$</span > </div>
    <% }); %>
</script>

js

addItem: function (item) {
        if (this.containsItem(item.id) === false) {
            this.items.push({
                id: item.id,
                name: item.name,
                price: item.price,
                count: item.count,
                total: item.price * item.count
            });
            storage.saveCart(this.items);
        } else {
            this.updateItem(item);
        }
        this.total += item.price * item.count;
        this.count += item.count;
        helpers.updateView();
    },
    containsItem: function (id) {
        if (this.items === undefined) {
            return false;
        }
        for (var i = 0; i < this.items.length; i++) {
            var _item = this.items[i];
            if (id == _item.id) {
                return true;
            }
        }
        return false;
    },
    updateItem: function (object) {
        for (var i = 0; i < this.items.length; i++) {
            var _item = this.items[i];
            if (object.id === _item.id) {
                _item.count = parseInt(object.count) + parseInt(_item.count);
                _item.total = parseInt(object.total) +parseInt(_item.total);
                this.items[i] = _item;
                storage.saveCart(this.items);
            }
        }

    }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use the filter function to remove an item, this way you are going to remove only the item that contains a specific id.

removeItem(id) {
   this.items = this.items.filter(item => item.id !== id);
}

To apply the coupon, unless you have all the coupons stored in your front-end, you should make an HTTPS call to check if the coupon is valid or not, but also its value to then apply the discount at the cart.

A suggestion to your code is related to containsItem function, where you iterate through the entire array and check every item id individually, and then return to the user. You can use the function some to let JS check it for you.

containsItem: function (id) {
   return this.items?.some(item => item.id === id);
}

//PS: the ?. is a notion that checks if the variable exists and if it's true it continues, that way you won't have an undefined error. It is called [Optional Chaining][2]

Another suggestion is on the updateItem, you can get the element that you need with the find function.

updateItem: function (object) {
   const itemToUpdate = this.items.find(item => item.id === object.id);
   if(itemToUpdate) {
      itemToUpdate.count = parseInt(object.count) + parseInt(itemToUpdate.count);
      itemToUpdate.total = parseInt(object.total) +parseInt(itemToUpdate.total);
      storage.saveCart(this.items);
  }
}

Also, you don't need to reassign the array, since when you refer to the object, it will be updated on its source as well.

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