Harriet
Harriet

Reputation: 1713

How to obtain row and column information of a clicked table

I have the following fiddle - where I am testing out a concept of getting to the data in a table. At the moment, I can get to the value displayed in a particular cell, when i click on the cell.

In addition, I would like to be able to get the row and column index of the clicked cell. Does anyone here know how to do this?

Link to fiddle

var tbl = document.getElementById("recordingTable");
if (tbl != null) {
    for (var i = 0; i < tbl.rows.length; i++) {
        for (var j = 0; j < tbl.rows[i].cells.length; j++)
        		
            tbl.rows[i].cells[j].onclick = function () { getval(this); };
    }
}
 
function getval(cel) {
    alert(cel.innerHTML);
    
}
<table cellspacing="1" id="recordingTable">

  <!-- this is the head element -->
  <thead class="callView">
    <!--specify the columns -->
    <tr>
      <th>STATE</th>
      <th>CALLID</th>
      <th>COLLECTED</th>
      <th>ZONE</th>
    </tr>
  </thead>
  
  <!-- -->
  <tbody class="callView">
    <tr>
      <td>0</td>
      <td>10001</td>
      <td>1</td>
      <td>0</td>
    </tr> 
    
    <tr>
      <td>1</td>
      <td>10002</td>
      <td>0</td>
      <td>1</td>
    </tr> 
    
    <tr>
      <td>0</td>
      <td>10003</td>
      <td>spring</td>
      <td>1</td>
    </tr> 
    
  </tbody>  
</table>

Upvotes: 0

Views: 514

Answers (2)

Gene R
Gene R

Reputation: 3744

Insead of adding onclick event to each cell you can add it to table, and get neccesary info from argument:

var tbl = document.getElementById("recordingTable");
tbl.onclick = function(e)
{
    console.log(e.target.innerHTML);
    console.log(e.target.cellIndex);
    console.log(e.target.parentElement.rowIndex);
}

JsFiddle: https://jsfiddle.net/19qfsxr9/14/

Upvotes: 3

Amaranadh Meda
Amaranadh Meda

Reputation: 724

You can get by using

cel.rowIndex
cel.cellIndex

in the function

Upvotes: 1

Related Questions