我试图从输入框中乘以2个值并将其存储在该列的最后一行。 添加效果非常好,但乘法不起作用。
我想将所有行输入相乘。我得到了一个例子,为什么不进行乘法运算?
我试过了
tot * = Number($(this).val())|| 0 //这不起作用。
tot =((tot)*(数字($(this).val())|| 0)) //这不起作用。
$('table input').on('input', function() {
var $tr = $(this).closest('tr'); // get tr which contains the input
var tot = 0; // variable to sore sum
$('input', $tr).each(function() { // iterate over inputs
tot += Number($(this).val()) || 0 // i want to multiply here. The addition works perfectly
});
$('td:last', $tr).text(tot); // update last column value
}).trigger('input'); // trigger input to set initial value in columns
答案 0 :(得分:3)
您也可以尝试使用此代码段。这里我指定了tot = 1
,因为乘以零会得到零结果。所以初始化不能为零,我将乘法语句修改为
"tot *= Number($(this).val())"
最终代码将是:
$('table input').on('input', function() {
var $tr = $(this).closest('tr');
var tot = 1; //variable to store product
$('input', $tr).each(function() {
tot *= Number($(this).val())
});
$('td:last', $tr).text(tot);
}).trigger('input');
答案 1 :(得分:2)
如果是添加,则在没有值时尝试添加0
。因此它不会影响添加中的任何内容。
但是如果你试图将整个值乘以0
,如果某个输入没有值,则整个值将变为零,并且将永远地重新调零。 Anything * 0 = 0.
所以改为:
tot *= Number($(this).val()) || 1
在乘法的情况下,初始化tot
的值为1
而不是0
。