2011-10-10 50 views
3

考慮下面的HTML表:自動計算爲兩列的總產品 - inolves動態錶行

<table id="myTable1"> 
    <tr id="TR1"> 
     <td><input type="text" id="quantity1" name="quantity1" /></td> 
     <td><input type="text" id="weight1" name="weight1" /></td> 
    </tr> 
</table> 

<table id="myTable2"> 
    <td><input type="text" id="total_weight" name="total_weight" /></td> 
</table> 

我想在這裏完成的是,我需要更新產品基於所述值total_weight字段值在重量鍵入每KEYUP()被觸發這些最後提及的兩個場的時間字段。所以基本上這就像total_weight + =(quantity * weight)

現在預計MYTABLE1將包含若干行,因爲作爲標題狀態,MYTABLE1是一個動態表,使得用戶可以在按下按鈕添加/刪除行---一個功能,我已經實施。

我有以下代碼計算用於total_weight數量列排除在外。我只需要弄清楚如何在數量上乘以重量乘以:

// Auto-compute (total weight) 
$('#myTable1 input[id^=\'weight\']').live('keyup',function() { 
    var total_weight = 0; 

    $('#myTable1 input[id^=\'weight\']').each(function(index, value) { 
     total_weight += Number($(this).val()); 

     $('#myTable2 #total_weight').val(total_weight); 
    }); 
}); 

回答

2

您與代碼非常接近。看看這個fiddle使用這個js ...

// Auto-compute (total weight) 
$('#myTable1 input[id^=weight], #myTable1 input[id^=quantity]').live('keyup',function() { 
    var total_weight = 0; 

    $('#myTable1 input[id^=weight]').each(function(index, value) { 
     var n = $(this).attr('id').substr(6); 
     total_weight += (Number($(this).val()) * Number($('#quantity' + n).val())); 
     $('#myTable2 #total_weight').val(total_weight); 
    }); 
}); 
+0

'非常感謝! –

+0

不客氣Angelo。 –