2016-06-10 84 views
0

所以我有,我不能現在小時解決問題..計算總和僅爲相關行

當我按下按鈕「Pridėtiprekę」然後一排動態添加到表,當我寫的「Kiekis」和「Kaina」列中的數字在「Suma」列中沒有任何反應(它只發生在動態添加的行中)。

片的jQuery:

$(document).on('keyup', '#quantity, #price', function() { 
    $('#total').val(($('#quantity').val() * $('#price').val()).toFixed(2)); 
}); 

請大家看的jsfiddle如何 「工作」 我的代碼:提前

https://jsfiddle.net/w5qz5exe/7/

感謝您的幫助!

P.S我試圖從div ID總數改變爲div class total,然後它可以工作,但它適用於所有行,而不是相關的。

回答

1

你正在引用id的所有內容。

$(document).on('keyup', '.quantity, .price', function() { 
     var row = $(this).closest('tr'); 
     var rowPrice = $(row).find('.price').val(); 
     var rowQuantity = $(row).find('.quantity').val(); 

     $(row).find('.total').val((rowPrice * rowQuantity).toFixed(2)) 
    }); 

https://jsfiddle.net/w5qz5exe/12/

+0

爲什麼你使用'獲得(0)'當設置'row'?只需分配jQuery對象並在函數的其餘部分使用它。 – Barmar

+0

你說得對。編輯。我只是喜歡使用$(row),因爲我可以輕鬆讀取代碼並查看所有jQuery對象的位置。 – wot

0

你的問題是這樣的事實,即輸入是使用id的而不是別的。在查找有問題的項目時,搜索停止在找到的第一個ID上。

這個更新的小提琴https://jsfiddle.net/w5qz5exe/11/顯示瞭如何用類來完成。

 $(document).on('keyup', '.quantity, .price', function(e) { 
      var $parent = $(e.target).parents('tr'), 
       $total = $parent.find('.total'), 
       $quantity = $parent.find('.quantity'), 
       $price = $parent.find('.price'); 
      $total.val(($quantity.val() * $price.val()).toFixed(2)); 
     }); 

除了上面的內容,將所有Id從輸入中移除並將它們改爲class。