Reputation: 22064
I have the following simple bit of jQuery which tells me what row/column a cell is inside of a table (excluding colspans).
var col = $this.index() + 1;
var row = $this.closest('tr').index() + 1;
Simple enough...except, my tables are nested inside other tables, and I don't know what the offset should be. For example, I have cell (1,1), this cell is in a table, which is in the second cell of another table... And that first cell has a table with three columns. So my cell is really (4,1)
EDIT: A more complete sample, with more test cases. I've nearly got it solved. Just some strange cases that are causing issues. (Now with coloured tests)
http://jsfiddle.net/gibble/J3uER/
...I realize this isn't normal, and the html is stupid, but it's what I need to work with.
Upvotes: 4
Views: 576
Reputation: 5660
I did it with iteration counters. It is a little bit complex, but your task too. :) And some html modifications are necessary: we have to mark main rows to differ them from nested rows. I added the class .row to reach this.
$('td').click(function (event) {
event.stopPropagation();
$(this).addClass('clicked');
var row = 0;
$('tr.row').each(function () {
row++;
if ( $(this).find('.clicked').length )
{
var td = 0;
$(this).find('td').each(function () {
if ( !$(this).find('td').length )
{
td++;
if ( $(this).is('.clicked') )
{
alert( 'row = ' + row + ', td = ' + td );
$('.row .clicked').removeClass();
}
}
}); // td each
}
}); // .row each
}); // td click
<table>
<tr class="row">
<td>A1</td>
<td>B1</td>
...
</tr>
<tr class="row">
<td>A2</td>
<td>B2</td>
...
</tr>
</table>
<table>
<tr class="row">
<td>
<table>
<tr>
<td>A3</td>
<td>B3</td>
...
</tr>
</table>
</td>
<td>
<table>
<tr>
<td>F3</td>
<td>G3</td>
...
</tr>
</table>
</td>
</tr>
</table>
Upvotes: 2