[英]jQuery Math Operation on Multiple Elements
I have a simple invoicing page so I can invoice my client, however when I am going to perform multiplication to the quantity and price, the row total is not adding. 我有一个简单的发票页面,因此可以为客户发票,但是,当我要对数量和价格进行乘法运算时,总行数未添加。 Here's my jQuery so far.
到目前为止,这是我的jQuery。
$(":input").bind('keypress keydown keyup change', function(){
var price = parseFloat($(this).closest('.tr').find('.price').val(),10),
var qty = parseFloat($(this).closest('tr').find('.quantity').val(),10);
var v = '';
if(!isNaN(price) && !isNaN(qty)) {
v = price * qty;
}
$(this).closest('tr').find('.rowtotal').val(v.toString());
});
And this is my HTML: 这是我的HTML:
<table>
<tr>
<td>1</td>
<td><input name="item_name[]"class="form-control"></td>
<td><input name="item_description[]"class="form-control"></td>
<td><input name="item_price[]"class="form-control price"></td>
<td><input name="item_quantity[]"class="form-control quantity"></td>
<td><span class="rowtotal">0.00</span></td>
</tr>
<tr>
<td>2</td>
<td><input name="item_name[]"class="form-control"></td>
<td><input name="item_description[]"class="form-control"></td>
<td><input name="item_price[]"class="form-control price"></td>
<td><input name="item_quantity[]"class="form-control quantity"></td>
<td><span class="rowtotal">0.00</span></td>
</tr>
</table>
Now on my page, it shows no error while reviewing the console, but it does not perform the operation that I have created following this post " Automatically updating input field with math using jquery? " 现在在我的页面上,在查看控制台时它没有显示任何错误,但是它不执行我在这篇文章“ 使用jquery使用数学自动更新输入字段? ”之后创建的操作。
Any help is appreciated. 任何帮助表示赞赏。
TIA TIA
You've got a typo in this line: 您在此行中有错别字:
var price = parseFloat($(this).closest('.tr').find('.price').val(),10),
^^ Shouldn't be a class selector
Should be: 应该:
var price = parseFloat($(this).closest('tr').find('.price').val(),10),
Next line is fine. 下一行很好。 Additionally, you can replace all those events with:
此外,您可以将所有这些事件替换为:
$(":input").on("input", function() {
// Triggers on any input event
});
You also have a few other issues: 您还有其他一些问题:
parseFloat
which takes two parameters parseFloat
没有重载,它有两个参数 .val()
to set the text of the span. .val()
来设置跨度的文本。 You need to use .text()
instead .text()
代替 <tr>
selector. <tr>
选择器。 You don't need to go find it each time. $(":input").on('input', function(){
var $tr = $(this).closest("tr");
var price = parseFloat($tr.find('.price').val()),
qty = parseFloat($tr.find('.quantity').val());
var v = '';
if(!isNaN(price) && !isNaN(qty)) {
v = price * qty;
}
$tr.find('.rowtotal').text(v.toString());
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.