tags:

views:

7110

answers:

5

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

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
.onClick should be .click
mkoryak
Which html spec do those attributes comply with? I can't seem to find them.
Stuart Branham
HTML spec 5, which allows for custom attributes starting with the prefix 'data-'.
Chris Brandsma
A: 

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
+19  A: 

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.

CMS
This doesn't work if there are column spans in the table
grom
+7  A: 

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;
});
Stuart Branham
Man its frustrating to spend 10 minutes thinking through a problem only to come back to StackOverflow to find someone has already posted the EXACT same code I came up with. Then again its kind of comforting.
Autodidact
A: 

I tried in many ways to solution this case in my table. I dont even remember of PREVALL (the key) of this. Thanks for share your knowledge.

Rio de Janeiro

Sergio Gumercindo