Calculating Quantity and Price for sub-total and grand total

问题内容:

When i check a checkbox, it displays the price of the item selected. Now when i click on the button increment or decrement, it multiplies the quantity against the price.

Now with my code, what happens is, when i check two items, cup and plates, the increment and decrement button for the first item skips 2 to 3 and it also controls the sub total for the second item as well.

Why is this happening?

function calc(product) {

  item = JSON.parse(product.dataset.product);

  if (product.checked == true) {
    $('.panel').append(
      '<p  class="price" data-price="' + product.price + '">' + product.price + '</p>' +
      '<p class="subtotal" ><span></span></p>' +
      '<div class="sp-quantity">' +
      '<div class="sp-minus fff"> <a class="ddd" href="#">-</a>' +
      '</div>' +
      '<div class="sp-input">' +
      '<input type="text" class="quantity-input" value="1">' +
      '</div>' +
      '<div class="sp-plus fff"> <a class="ddd" href="#">+</a>' +
      '</div>' +
      '</div>' +
      '</div>'
    )

    $(".ddd").on("click", function() {

      var $button = $(this),
        $input = $button.closest('.sp-quantity').find("input.quantity-input");
      var oldValue = $input.val(),
        newVal;

      if ($.trim($button.text()) == "+") {

        newVal = parseFloat(oldValue) + 1;
      } else {
        // Don't allow decrementing below zero
        if (oldValue > 0) {
          newVal = parseFloat(oldValue) - 1;
        } else {
          newVal = 0;
        }
      }

      $input.val(newVal);
      var grandTotal = 0;
      var product;

      $('.panel .container').each(function() {
        product = $(this),
          quantity = newVal,
          price = Number(product.find('.price').data('price')),
          points = Number(product.find('.points').data('points')),
          total = quantity * price; //

        product.find('.subtotal span').text(total);
        grandTotal += total;

      });

      $('.checkout span').text(grandTotal);

    });

  } else {
    var total = $(".panel .container [data-id=" + product.id + "]").parent().find(".subtotal").text();
    $(".panel .container [data-id=" + ad.id + "]").parent().remove();

    if (total) {
      $('.checkout span').text(function(index, oldtext) {
        alert(oldtext);
        console.log('this is my old text ' + oldtext)
        return oldtext ? oldtext - total : oldtext;
      });
    }
  }
}

问题评论:

原文地址:

https://stackoverflow.com/questions/47755943/calculating-quantity-and-price-for-sub-total-and-grand-total

添加评论

友情链接:蝴蝶教程