Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: getting td index [duplicate]

Tags:

jquery

xhtml

Possible Duplicate:
Table row and column number in jQuery

If I have a table like so:

<table>
  <thead>
     <tr><th>1</th> <th>2</th> <th>3</th></tr>
  </thead>

  <tbody>
    <tr><td>data</td> <td>checkbox</td> <td>data</td></tr>
  </tbody>
</table>

When the user clicks the checkbox, I want to get the row and column indices. I can get the row index by using this code:

 var row = $(this).parent().parent();
 var rowIndex = $(row[0].rowIndex);

but I can't figure out the column index...

I tried this but it didn't work:

 var colIndex = $(row.children().index(this).parent());

I looked through the results of similar questions here and it seems I have to iterate through all the tds with each or map, is there something simpler that I can use? Thanks.

like image 556
PruitIgoe Avatar asked Jun 24 '11 16:06

PruitIgoe


1 Answers

Get the index of the <td> first, since it is on the way to the <tr>:

var cell = $(this).closest('td');
var cellIndex = cell[0].cellIndex

var row = cell.closest('tr');
var rowIndex = row[0].rowIndex;

Or using the parents()[docs] method along with a multiple-selector[docs], you could do the selection for both at once:

var cellAndRow = $(this).parents('td,tr');

var cellIndex = cellAndRow[0].cellIndex
var rowIndex = cellAndRow[1].rowIndex;
like image 120
user113716 Avatar answered Oct 04 '22 00:10

user113716