khemikal khemikal - 1 year ago 50
Javascript Question

jquery function calculation no working right on second call

I have a subtotals function that does some calculations on an html table (sums up columns that have assigned classes). I have modified it so that I can pass arguments to it, and on the first function call it works as desired. When I call it again it creates the cell and assigns the class, but the math or apparently something else is wrong because it is returning NaN. Here is my JSFiddle and below is my function. Any help would be appreciated!

//v is parent,z is child element,w is which child column....ex: 0 or 1, y is first run or not, z is class name you want assigned
function subtotals(v, w, x, y, z) {
$(v).each(function (index, element) {
var subTotalAmt = 0;
var numRows = parseInt($(this).attr("rowspan"));
var firstRow = $(this).parent();
var lastRow = firstRow.nextAll('tr').slice(numRows - 2, numRows - 1);
var currentRow = firstRow;
for (i = 0; i < numRows; i++) {
subTotalAmt += parseInt($(currentRow.children(w)[x]).text());
currentRow ="tr");
if(y == 'yes'){
lastRow.after('<tr><td class="sub0">Sub Total</td><td class="' + z + '">' + subTotalAmt + '</td></tr>');
$(this).attr('rowspan', numRows + 1);
else {
lastRow.append('<td class="' + z + '">' + subTotalAmt + '</td>');
$(function doSubtotals() {

Answer Source

Some of your <td> are not containing a valid number , which case the calculation to fail and put NaN (stands for 'Not a Number') instead of a valid number (NaN + number = NaN). To fix this i added this condition to your code :

  for (i = 0; i < numRows; i++) {
        var tdValue=0;
        subTotalAmt += tdValue;
        currentRow ="tr");