Reputation: 81
i have a problem with the code below, I want to sum alla input values for a tr and that works good except that it show the row values on all rows instead of the changed one. Code below:
$(".txtMult input").keyup(multInputs);
function getNum($val) {
if (isNaN($val)) {
return 0;
} else {
return $val;
}
}
function multInputs() {
var mult = 0;
var $total = 0;
// for each row:
$("tr.txtMult").each(function () {
var $total = 0;
$("input.val").each(function () {
// get the values from this row:
$total = +parseFloat($total)+getNum(parseFloat($(this).val()));
});
$('.multTotal',this).text($total);
});
}
any suggestions ?
Example on JSfiddle
Upvotes: 0
Views: 97
Reputation: 26844
that it show the row values on all rows instead of the changed one
The way I understand this statement is you only want to show the Total
of the rows that have changed or have values, then you can just add an if/else
statement like:
function multInputs() {
var mult = 0;
// for each row:
$("tr.txtMult").each(function () {
// get the values from this row:
var $val1 = $('.val1', this).val();
var $val2 = $('.val2', this).val();
var $total = ($val1 * 1) * ($val2 * 1)
if ( $total != 0 && !isNaN($total) ) {
$('.multTotal',this).text($total);
mult += $total;
} else $('.multTotal',this).text("");
});
$("#grandTotal").text(mult);
}
Here is the fiddle: http://jsfiddle.net/5FpWC/540/
I also added a condition to only show if valid number - !isNaN($total)
Update:
Regarding the new update on this fiddle: http://jsfiddle.net/5FpWC/541/
The error is in $("input.val")
, You are selecting all the input
with class val
on all tr
s.
Yous should use $(this).find("input.val")
to specify that you only want the input.val
on the current tr
on the loop.
$("tr.txtMult").each(function () {
var $total = 0;
$(this).find("input.val").each(function () {
// get the values from this row:
$total = +parseFloat($total)+getNum(parseFloat($(this).val()));
});
$('.multTotal',this).text($total);
});
Fiddle: http://jsfiddle.net/5FpWC/543/
Upvotes: 1