gpt4 book ai didi

javascript - 计算表行并填充总计字段

转载 作者:行者123 更新时间:2023-12-01 02:23:01 25 4
gpt4 key购买 nike

我有如下表:

<table>
<thead>
<th>Product Type</th>
<th>Quantity</th>
<th>Unit</th>
<th>Total</th>
</thead>
<tr>
<td>Gas</td>
<td><input type="text" name="qty" /></td>
<td>
<select id="unit" name="unit">
<option value="30.42">Liter</option>
<option value="25.30">Ton</option>
<option value="45.10">Kg</option>
</td>
<td><input type="text" readonly="readonly" name="total" /></td>
</tr>
<tr>
<td>Diesel</td>
<td><input type="text" name="qty" /></td>
<td>
<select id="unit" name="unit">
<option value="20.42">Liter</option>
<option value="18.30">Ton</option>
<option value="25.10">Kg</option>
</td>
<td><input type="text" readonly="readonly" name="total" /></td>
</tr>
<tr>
<td>Fuel</td>
<td><input type="text" name="qty" /></td>
<td>
<select id="unit" name="unit">
<option value="30.42">Liter</option>
<option value="25.30">Ton</option>
<option value="45.10">Kg</option>
</td>
<td><input type="text" readonly="readonly" name="total" /></td>
</tr>

我想根据qtyunit计算(qty * unit)每行,并将结果放入total列。

在计算结束时,我想对整个 total 字段进行求和并放入 Grand Total 字段。

我尝试如下,总是返回 NaN 但当我通过 typeof 检查值时返回 number! :

$(document).ready(function() {  
$('input[name^=qty], select[name^=unit]').change(function(){
var total = 0;
var $row = $(this).parent();
var qty = parseFloat($row.find('input[name=qty]').val());
var price = parseFloat($row.find("select[name='unit'] option:selected").val());
total = parseFloat(qty * price);
$row.find('.amount').text(parseFloat(qty * price));
})
});

最佳答案

此处存在多个错误,包括在输入字段上使用 text() 以及使用 parent() 而不是 closest("tr")

我还向您的元素添加了类,以使选择器更容易。试试这个:

$('.qty, .unit').change(function(){  
var total = 0;
var $row = $(this).closest("tr");
var qty = parseFloat($row.find('.qty').val());
var price = parseFloat($row.find(".unit").val());
total = parseFloat(qty * price);
$row.find('.total').val(parseFloat(qty * price));
})

Example fiddle

<小时/>

更新

为选择添加了空白默认值:

$('.qty, .unit').change(function(){  
var total = 0;
var $row = $(this).closest("tr");
var qty = parseFloat($row.find('.qty').val());
var price = parseFloat($row.find(".unit").val());
total = qty * price;

if (isNaN(total)) {
$row.find('.total').val("");
}
else {
$row.find('.total').val(total);
}
})

Fiddle

关于javascript - 计算表行并填充总计字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10533238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com