147

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 = ...
});
Jonas
  • 19,422
  • 10
  • 54
  • 67

6 Answers6

226

You can use the Core/index function in a given context, for example you can check the index of the TD in it's parent TR to get the column number, and you can check the TR index on the Table, to get the row number:

$('td').click(function(){
  var col = $(this).parent().children().index($(this));
  var row = $(this).parent().parent().children().index($(this).parent());
  alert('Row: ' + row + ', Column: ' + col);
});

Check a running example here.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
124
$('td').click(function() {
    var myCol = $(this).index();
    var $tr = $(this).closest('tr');
    var myRow = $tr.index();
});
Phillip Senn
  • 46,771
  • 90
  • 257
  • 373
36

Get COLUMN INDEX on click:

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

Get ROW INDEX on click:

$(this).closest("tr").index();
Pablo Claus
  • 5,886
  • 3
  • 29
  • 38
Louie Santiano
  • 361
  • 3
  • 2
22

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;
});
Samantha Branham
  • 7,350
  • 2
  • 32
  • 44
6

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");
}
Chris Brandsma
  • 11,666
  • 5
  • 47
  • 58
0

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

mkoryak
  • 57,086
  • 61
  • 201
  • 257
  • While this might be a valuable hint to solve the problem, a good answer also demonstrates the solution. Please [edit] to provide example code to show what you mean. Alternatively, consider writing this as a comment instead. – Toby Speight May 16 '17 at 12:26
  • 1
    thanks, I will consider revising this answer in another 10 years – mkoryak Oct 16 '18 at 18:40