Remove items and change total value

Asked

Viewed 367 times

1

Hello, I have a problem that I have been racking my brain for a long time and I just can’t understand why it happens... In my application I have a cart that so far inserts products normally, does the sum of their values and adds to the total, however, when I try to remove an item from the cart it is simply messing up the total amount

inserir a descrição da imagem aqui

For example, when I remove Tuna which is the first item from the list, it simply subtracts the triplicate value, if I remove the salmon which is the second item from the list, it removes duplicate...

Example removing the Tuna:

inserir a descrição da imagem aqui

The value is negative and on the console it is as if it had been removed 3x with a single click...

In the elements it was deleted correctly until

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

Follow the codes I used to create the elements, remove and update the total value of the cart when deleted some item:

Creation of items

$(document).ready(function(){
var btnAdcionaCarrinho = $(".btn-adicionar-carrinho");
btnAdcionaCarrinho.click(function(){
    adicionaProduto($(this));
    totalPedido(buscaItensPedido());
});
});
function adicionaProduto(el){ //adiciona produto ao carrinho
    console.log(el);
    var nomeProduto = el.parent().find(".titulo-produto");
    var qtdProduto = el.parent().find(".qtd-produto").val();
    var precoProduto = el.parent().find(".preco-produto").text();
 
    alteraQtdItensCarrinho("add");
    buildItemPedido(nomeProduto.text(),qtdProduto,precoProduto);
    carrinho.find(".btn-remover-item").click(function(){
        console.log($(this));
        alteraQtdItensCarrinho("del");
        removeProduto($(this));
    });
  
}

function buildItemPedido(nomeProduto,qtdProduto,precoProduto){//cria a linha na tabela contendo as informações sobre o pedido
    var novoItem = $("<tr></tr>");
   
    var nomeItem = $("<td></td>").addClass("nome-pedido").text(nomeProduto);
    var qtdItem = $("<td></td>").addClass("qtd-pedido").text(qtdProduto);
    var qtdPrecoItem = $("<td></td>").addClass("qtd-preco-pedido").text(precoProduto);
    var removerItem = $("<td></td>").addClass("remover-item");
    var botaoRemover = $("<span></span>").append("<i></i>").addClass("icon-close btn-remover-item");
    removerItem.append(botaoRemover);
   
    novoItem.append(nomeItem,qtdItem,qtdPrecoItem,removerItem);
    carrinho.append(novoItem);
    
    console.log(novoItem);
    console.log(carrinho);
    return carrinho;
}

Item removal

function removeProduto(el){// deleta produto do carrinho
    var item = el.parent().parent();
    var itemPreco = item.find(".qtd-preco-pedido").text();
    var itemQtd = item.find(".qtd-pedido").text();
    console.log(item,itemPreco,itemQtd);
    
    subtraiValorTotal(itemPreco,itemQtd);
    
    item.remove();
}

Change in total value

function subtraiValorTotal(itemPreco,itemQtd){//diminui o valor total quando um item é removido
   // console.log(itemPreco,itemQtd);
    var precoItem = parseFloat(removeSifrao(itemPreco).replace(",",".")) * parseInt(itemQtd);
    var total = parseFloat(removeSifrao($("#valor-total").text()).replace(",","."));
   // console.log(precoItem.toFixed(2));
   // console.log(total);
    var novoTotal = total - precoItem;
    $("#valor-total").text("R$" + novoTotal.toFixed(2).toString().replace(".",","));
}

  • Good question, I go here in the neighbor to check if he has the HTML so we can reproduce the problem.

  • What do you have in that role removeSifrao()?

  • It removes the R$ of the order, since when I add some item to the cart it ends up going in string form (example: R$ 40,00) and need to perform calculations and for this it removes through a Regex the R$ and returns me the converted value already to float

  • As for HTML, it is basically a table without <tr> any, I create them in the buildItemPedido function when I add a product to the cart

  • He’s got a lot of code flaws.

1 answer

1


There are some problems in the codes that should be fixed. Here for example:

novoTotal.toFixed(2).toString().replace(".",",")

Why .toString() if the .toFixed(2) already converts number into string? It’s redundant to do so. You’re converting string into string.

I don’t know what your job is removeSifrao but this one can handle:

function removeSifrao(i){
   i = i.replace("R$","").replace(".","").replace(",",".");
   i = parseFloat(i).toFixed(2);
   return i;
}

See that you can treat the number within the function and return it cleaner than using parseFloat in the middle of the codes.

Compare the example code working below with yours and make the corrections:

function removeSifrao(i){
   i = i.replace("R$","").replace(".","").replace(",",".");
   i = parseFloat(i).toFixed(2);
   return i;
}

function removeProduto(el){// deleta produto do carrinho
    var item = $(el).closest("tr");
    var itemPreco = item.find(".qtd-preco-pedido").text();
    var itemQtd = item.find(".qtd-pedido").text();
    subtraiValorTotal(itemPreco,itemQtd);
    item.remove();
}

function subtraiValorTotal(itemPreco,itemQtd){//diminui o valor total quando um item é removido
    var precoItem = (removeSifrao(itemPreco) * itemQtd).toFixed(2);
    var total = removeSifrao($("#valor-total").text());
    var novoTotal = total - precoItem;
    $("#valor-total").text("R$" + novoTotal.toFixed(2).replace(".",","));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
   <tr>
      <td>prod 1</td>
      <td class="qtd-pedido">5</td>
      <td class="qtd-preco-pedido">R$5,80</td>
      <td><button onclick="removeProduto(this)">X</button></td>
   </tr>
   <tr>
      <td>prod 2</td>
      <td class="qtd-pedido">3</td>
      <td class="qtd-preco-pedido">R$10,90</td>
      <td><button onclick="removeProduto(this)">X</button></td>
   </tr>
   <tr>
      <td>prod 3</td>
      <td class="qtd-pedido">3</td>
      <td class="qtd-preco-pedido">R$5,90</td>
      <td><button onclick="removeProduto(this)">X</button></td>
   </tr>
</table>
Total: <div id="valor-total">R$79,40</div>

Another thing, to make multiplications and divisions of numbers, do not need to convert the type (use parseInt or parseFloat). It would only be necessary in case of addition or subtraction.

  • Now everything works correctly x.x I’m still starting with JS and still have a lot to learn xD Little did I know that replace already converts to String... Thank you for sharing an extra knowledge =D

  • replace no, the toFixed that converts to string :)

  • ops, exact kkkkk

  • Most obvious!...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.