sm1l3y sm1l3y - 6 months ago 20
jQuery Question

JQuery - Get value of cell directly above current cell

I am working on a function that needs to return the sum of the cell to the left and the cell above the current cell. So left of cell + above cell = cell contents.

My code:

$('#' + value + ' .runningStore').each(function () {
$.each(this.cells, function () {
if (!isNaN(parseInt($(this).prev('tr').text()))) {
var td1 = parseInt($(this).prev('tr').text());
if (!isNaN(parseInt($(this).prev().text()))) {
var td2 = parseInt($(this).prev().text());
var sum = (td1 + td2);

I am able to successfully get the value of the cell to the left (var td2), but I cannot seem to figure out or find a working example (or figure out on my own) of getting the cell above the current cell.

The function is to loop through the entire row and for each cell sum left of cell + cell above.


You need to save the index of the current cell, var = index, search for the previous tr and then find its child with the same index, var = prevRow.

I code, something like this:

var index =  $(this).index();
var prevRow = $(this).closest('tr').prev().find('td:nth-child('+index+')').text();

if ( !isNaN(parseInt(prevRow)) ) {
    var td1 = parseInt(prevRow);

A codepen to better help you understand (check the console to see the output)

One tip: - use variables to avoid duplicated code.