0

我有一些代码可以在将数据插入现有行时附加新的表行。

您可以在此处查看正在运行的代码。

输入产品时,新行将附加到具有唯一输入名称的表中。

然后要求用户输入价格和数量。

我想要的是两步计算。在输入框 Total 中,我想要该price * qty特定行的总和。其次,我希望 divgrandtotal显示所有输入框的总和,所有输入框都是动态的,以用户插入的行数为准。

通常我只会使用:

function fill() {
    var txt8 = document.getElementById("TextBox8").value;
    var txt9 = document.getElementById("TextBox9").value;
    document.getElementById("TextBox10").value = txt8 + txt9;
}

但这是一个静态的静态表,其中名称和 ID 是已知的。如何使这项工作适用于动态生成的表?

抱歉,我忘了给你小提琴链接:http: //jsfiddle.net/yUfhL/230/

4

1 回答 1

2

To get all inputs that have an ID that starts with linetotal, you could write the following in jQuery:

$('input[id^=linetotal]')

Now, to calculate the total, just iterate over the collection:

var total = 0;
$('input[id^=linetotal]').each(function() { 
    total += parseInt(this.value, 10) || 0; 
});

Your output, then:

$('#grandtotal').text(total);

Edit

To first calculate the line totals for every line, you could iterate through them like so:

$('table.order-list tr').each(function() {
   var price = parseInt( $('input[name=price]', this).val(), 10 );
   var qty   = parseInt( $('input[name=qty]'  , this).val(), 10 );
   $('input[id^=linetotal]', this).val(price * qty);
});

Of course, you wouldn't have to iterate over all rows at all times. At the change event, you're only interested in the current row, which is accessible by $(this).closest('tr')

于 2013-03-27T13:48:57.737 回答