LucasSeveryn LucasSeveryn - 3 months ago 12
Javascript Question

How to set value of a cell by row and column index?

I have this so far, but it doesn't change the cell value:

function setCellValue(tableId, rowId, colNum, newValue)
{
$('#'+tableId).find('tr#'+rowId).find('td:eq(colNum)').html(newValue);
};

Answer

Create selector by concatenating index (in :eq() index starts from 0). Although you need to do the same with row selector since rowId is the index of tr not an id.

function setCellValue(tableId, rowId, colNum, newValue)
{
    $('#'+tableId).find('tr:eq(' + (rowId - 1) + ')').find('td:eq(' + (colNum - 1) + ')').html(newValue);
};

Or use :nth-child() pseudo-class selector.

function setCellValue(tableId, rowId, colNum, newValue)
{
    $('#'+tableId).find('tr:nth-child(' + rowId + ')').find('td:nth-child(' + colNum + ')').html(newValue);
};

Or with single selector by avoiding find() method.

function setCellValue(tableId, rowId, colNum, newValue)
{
    $('#' + tableId + ' tr:nth-child(' + rowId + ') td:nth-child(' + colNum + ')').html(newValue);
    // or
    $('#' + tableId + ' tr:eq(' + (rowId - 1) + ') td:eq(' + (colNum - 1) + ')').html(newValue);
};