2015-10-16 79 views
0

我有一個產品網頁,將輸入的成本,數量和服用的2添加輸入字段

我已經想通了這裏http://jsfiddle.net/61tch8md/大部分產品後吐出成本的多個級別(我相信)但我遇到的問題是,用戶可以添加多行,每行只需要添加該行上的字段的數量和成本。現在,當我添加額外的行時,第一行將控制所有行的價格。

HTML

<table class="order-details"> 
    <tbody> 
    <tr> 
     <td><input type="text" value="" placeholder="Description of Work" class="wei-add-field description 1" name="product-1-description" /></td> 
     <td><input type="text" value="" placeholder="QTY" class="wei-add-field quantity 1" name="product-1-quantity" /></td> 
     <td><span class="wei-price">$</span><input type="text" value="" placeholder="Unit Price" class="wei-add-field unit-price 1" name="product-1-price"/></td> 
     <td><span class="wei-price-total"></span></td> 
     <td> </td> 
    </tr> 
    </tbody> 
</table> 

<div class="wei-add-service"><a href="#" class="button-secondary wei-add-service-button">Add Item</a></div> 

的JavaScript/jQuery的

jQuery("tr") 
    .keyup(function() { 
    var value = jQuery(".unit-price").val(); 
    var value2 = jQuery(".quantity").val(); 
    var total = value * value2; 

    jQuery(".wei-price-total").text(total); 
    }) 
    .keyup() 

var counter = 2; 
jQuery('a.wei-add-service-button').click(function(event){ 
    event.preventDefault(); 
    counter++; 
    var newRow = jQuery('<tr><td><input type="text" value="" placeholder="Description of Work" class="wei-add-field description" name="product-' + 
     counter + '-description" /></td><td><input type="text" value="" placeholder="QTY" class="wei-add-field quantity" name="product-' + 
     counter + '-quantity" /></td><td><span class="wei-price">$</span><input type="text" value="" placeholder="Unit Price" class="wei-add-field unit-price" name="product-' + 
     counter + '-price"/></td><td><span class="wei-price-total">$49.99</span></td><td><a href="#" class="remove">remove</a></td></tr>'); 
    jQuery('table.order-details').append(newRow); 
}); 


jQuery('table.order-details').on('click','tr a',function(e){ 
e.preventDefault(); 
jQuery(this).parents('tr').remove(); 
}); 

在此先感謝。

回答

1

更改您的代碼,以便選擇keyup發生的行中的輸入。

jQuery('table.order-details').on("keyup", "tr", function() { 
    var row = jQuery(this); 
    var value = jQuery(".unit-price", row).val(); 
    var value2 = jQuery(".quantity", row).val(); 
    var total = value * value2; 

    jQuery(".wei-price-total", row).text(total); 
    }); 
+0

我更新了它,現在它只編輯第一行。當我添加額外的行時,它們根本不會更新http://jsfiddle.net/61tch8md/1/ –

+0

您需要使用事件委託來將處理程序綁定到動態添加的行。就像你對刪除行的函數一樣。我已經更新了答案,以顯示如何編碼。 – Barmar