2017-02-01 3 views
0

このコードはありますが、正しく機能していません。複数の入力値が1つの合計を加算または減算する

アイデアは、すべての入力に値があり、上下をクリックすることによって合計値からその値を減算することです。

今はちょうど追加と追加と狂気のような追加です。

ありがとうございました。

JS

ここでは例
$(document).ready(function() { 
    $(".quantity").each(function(){ 
     $(this).change(function(){ 
      var quantity = ($(this).val()); 
      var ammount = ($(this).attr("data-price")); 
      var price = $(this).closest(".bookSection").find(".item_price").html(); 
      var subtotal = ammount * quantity; 
      var total = parseInt(subtotal) + parseInt(price); 
      $(this).closest(".bookSection").find(".item_price").html(total); 
     }); 
    }); 
}); 

http://jsbin.com/tolequyobi/1/edit?html,js,output

+0

のようなものに数量が変わるたびに行うことができます。あなたは決して価格から何も引くことはありません。 – Jerrad

答えて

2

代わりの.item_priceがちょうど最初からそれを計算に使用しようとしています。そうでない場合は、追加または削除する必要があるかどうかを知るために古い値を保存する必要があります。

あなたが価格に小計を追加している、この

$('.quantity').change(function(){ // check change on the inputs 
    var total = 0; // set the total to 0 
    $(this).parent().find('.quantity').each(function() { // loop on all the items thats in this block 
     total += parseInt($(this).attr('data-price')) * parseInt($(this).val()); // add to the total their value 
    }); 
    $(this).parent().find(".item_price").html(total); // and then add it to your html 
}); 
+0

マジック...完璧に動作します。 ありがとうございました! – ysanmiguel

1

どの量が変化するたびに一から合計を再計算するのではなく、あなたは維持する必要が実行されている合計を維持しようとしてはどうですか?

$(document).ready(function() { 
    var price = 0; 
    $(".quantity").each(function(){ 
     $(this).change(function(){   
      var total = computeTotal($(this).closest(".bookSection")); 
      $(this).closest(".bookSection").find(".item_price").html(total); 
     }); 
    }); 
}); 

function computeTotal(bookSection){ 
    var total=0; 
    bookSection.children('.quantity').each(function(item){ 
    total += $(this).val() * $(this).attr("data-price"); 
    }); 
    return total; 

http://jsbin.com/rimubocijo/edit?html,js,output

関連する問題