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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With