Table row and column number in jQuery

Jquery

Jquery Problem Overview


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 = ...
});

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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

Solution 3 - Jquery

Get COLUMN INDEX on click:

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

Get ROW INDEX on click:

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

Solution 4 - Jquery

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;
});

Solution 5 - Jquery

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");
}

Solution 6 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonasView Question on Stackoverflow
Solution 1 - JqueryChristian C. SalvadóView Answer on Stackoverflow
Solution 2 - JqueryPhillip SennView Answer on Stackoverflow
Solution 3 - JqueryLouie SantianoView Answer on Stackoverflow
Solution 4 - JquerySamantha BranhamView Answer on Stackoverflow
Solution 5 - JqueryChris BrandsmaView Answer on Stackoverflow
Solution 6 - JquerymkoryakView Answer on Stackoverflow