[jquery] Table row and column number in jQuery

How do I get the row and column number of the clicked table cell using jQuery, i.e.,

$("td").onClick(function(event){
   var row = ...
   var col = ...
});

This question is related to jquery

The answer is


Off the top of my head, one way would be to grab all previous elements and count them.

$('td').click(function(){ 
    var colIndex = $(this).prevAll().length;
    var rowIndex = $(this).parent('tr').prevAll().length;
});

Get COLUMN INDEX on click:

$(this).closest("td").index();

Get ROW INDEX on click:

$(this).closest("tr").index();

Can you output that data in the cells as you are creating the table?

so your table would look like this:

<table>
  <thead>...</thead>
  <tbody>
    <tr><td data-row='1' data-column='1'>value</td>
      <td data-row='1' data-column='2'>value</td>
      <td data-row='1' data-column='3'>value</td></tr>

  <tbody>
</table>

then it would be a simple matter

$("td").click(function(event) {
   var row = $(this).attr("data-row");
   var col = $(this).attr("data-col");
}

its better to bind a click handler to the entire table and then use event.target to get the clicked TD. Thats all i can add to this as its 1:20am


$('td').click(function() {
    var myCol = $(this).index();
    var $tr = $(this).closest('tr');
    var myRow = $tr.index();
});