Get html table row and cell index with javascript function

Viewed 288

I neet to return row and cell index according to user click in table.

My function:

function updatePrice()
{
    var rIndex, cellIndex, table = document.getElementsByTagName('table')[0];

    for(var i = 0; i < table.rows.length; i++){
        table.rows[i].onclick = function valorLinha() {
            rIndex = this.rowIndex;
            /*console.log here works fine*/
        };
        for (var j = 0; j < table.rows[i].cells.length; j++)
            table.rows[i].cells[j].onclick = function () {
                cellIndex = this.cellIndex;
        };

  
        /*I NEED values of rIndex and cellIndex here*/
        console.log(rIndex);
        console.log(cellIndex);
    }
}

I'm getting undefined when console.log runs.

How can I solve this?

3 Answers

 document.querySelectorAll('#table td')
.forEach(e => e.addEventListener("click", function() {
    // Here, `this` refers to the element the event was hooked on
    console.log("clicked cell at: " + this.cellIndex + ", " + this.parentNode.rowIndex);
}));
td{
cursor:pointer;
}
<table id="table">
    <tbody>
      <tr>
        <td>00</td>
        <td>10</td>
      </tr>
      <tr>
        <td>01</td>
        <td>11</td>
      </tr>
      <tr>
        <td>02</td>
        <td>12</td>
      </tr>
    </tbody>
  </table>

var table = document.getElementsByTagName('table')[0];
for (let i = 0; i < table.rows.length; i++) {
    for (let j = 0; j < table.rows[i].cells.length; j++){
        table.rows[i].cells[j].onclick = function(){
            console.log("Row = "+i+" Cell = "+j)
        }
    }
}

rIndex is the same as i variable in the loop and cellIndex is a collection you should loop it

function updatePrice()
{
    var rIndex, cellIndex, table = document.getElementsByTagName('table')[0];

    for(var i = 0; i < table.rows.length; i++){
        var rowi = table.rows[i];
        // rIndex = rowi.rowIndex = i;
        rIndex = i;
        console.log(rIndex);

        // cellIndex are multiple, you should loop

        for (var j = 0; j < rowi.cells.length; j++){
            var cellj = rowi.cells[j];
            cellIndex = cellj.cellIndex;console.log(cellIndex);
        } 
    }
}```
Related