sm1l3y sm1l3y - 4 months ago 11
Javascript Question

Multiplying values of cells returning nothing

I have a function that loops over rows and captures the values in certain cells. It successfully does that, and I am able to return those individual values even. However when I try and multiple them it returns nothing. Here is my JSFiddle

Here is my function:

$('#' + value + ' .totalRacks').each(function() {
$.each(this.cells, function() {
var index = $(this).index() + 1;
var prevRow0 = $(this).closest('tr').prev().find('td:nth-child(' + index + ')');
var prevRow1 = $(this).closest('tr').prev().prev().prev().find('td:nth-child(' + index + ')');
if (!isNaN(parseInt(prevRow0.text()))) {
var td1 = parseInt(prevRow0.text());
}
if (!isNaN(parseInt(prevRow1))) {
var td2 = parseInt(prevRow1);
}
var product = parseInt((td1 * td2));
$(this).html(product);
});
});

Answer

You have a couple of logic issues. Firstly you can loop through the td cells using a single each() call and you missed the retrieval of the text() of the prevRow1. If you fix those issues the code works. You can also tidy the isNaN checks by defaulting the values to 0. Try this:

$('#' + value + ' .totalRacks td:not(:first, :last)').each(function() {
    var index = $(this).index() + 1;
    var prevRow0 = $(this).closest('tr').prev().find('td:nth-child(' + index + ')');
    var prevRow1 = $(this).closest('tr').prev().prev().prev().find('td:nth-child(' + index + ')');

    var td1 = parseInt(prevRow0.text(), 10) || 0;
    var td2 = parseInt(prevRow1.text(), 10) || 0;    
    var product = parseInt(td1 * td2);
    $(this).html(product);
});

Updated fiddle