Adding variables in javascript

Asked

Viewed 61 times

1

Hello! I have the following code:

 $(document).ready(function(){
  $('.buttonAdd').click (function(){
    $(this).closest('.row').find('.inputQtd').val();
    var iqtd = $(this).closest('.divAddProdutosPagamentos').find('.inputQtd');
    var qtd = Number(iqtd.val());
    iqtd.val(qtd+1);
    var badgeCount = badgeCount + qtd+1;
    $('#badgeCarrinho').text(badgeCount);
  });
});

Basically, every time the user clicks on the '.buttonAdd' will add one more. The system is a market cart, so there are several products in the cart. My 'badgeCount' variable should display the total of items in the cart, that is, if Voce added 2 rice and 2 beans, my badgeCount variable should display 4. In java is easy, I make badgeCount += Qtd. Because it will store the total. But in javascript I am not able to do this. Could someone help me? The image serves to improve the explanation: inserir a descrição da imagem aqui

As you can see, I have 3 items in my cart, and I would like my variable badgeCount to store the total of these 3 items (in case 6).

(The badgeControl variable is displayed in the upper right corner, next to the cart icon)

1 answer

1


Just go through each quantity input with .each() and add the values. Note that the variable badgeCount beginning of 0:

$(document).ready(function(){
   $('.buttonAdd').click (function(){
      var iqtd = $(this).closest('.divAddProdutosPagamentos').find('.inputQtd');
      var qtd = Number(iqtd.val());
      iqtd.val(qtd+1);

      var badgeCount = 0;

      $(".inputQtd").each(function(){
         badgeCount += Number($(this).val());
      });

      $('#badgeCarrinho').text(badgeCount);
   });
});

Browser other questions tagged

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