15

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.

Community
  • 1
  • 1
PruitIgoe
  • 6,166
  • 16
  • 70
  • 137
  • Well, one problem is that you need to nest tags inside tags. I don't think it is legal to put them directly in a tag. – JohnFx Jun 24 '11 at 16:39
  • They are I just forgot to add them in the question example...it is Friday. : D I edited it. – PruitIgoe Jun 24 '11 at 16:42
  • May I ask what you are doing with the row/column indexes? We might have an idea for an alternative where you don't need it. – JohnFx Jun 24 '11 at 16:44
  • Just replacing the checkbox with some text -> process is user clicks the checkbox, i use uiBlock to show a form on the screen that simply ask for the user name to be input, its validated, then that name is placed in the cell of the checkbox clicked. This is for a workflow site for products for an ecommerce site, so the checkbox cell (in this case) is if artwork has been provided and by who. – PruitIgoe Jun 24 '11 at 16:48
  • Got it working: var colIndex = row.children().index($(this).parent()); was omitting the $ – PruitIgoe Jun 24 '11 at 16:55
  • @PruitIgoe - feel free to add your own answer and accept it. – Brandon Boone Jun 24 '11 at 16:59
  • @Pruitlgoe, your code is all on crack, my friend. `$(this).parent().parent()`? What if you end up nesting it in another tag? It simply gets hosed. Read up on `closest`:http://api.jquery.com/closest/ My guess is that you want `$(this).closest('tr');` – Levi Morrison Jun 24 '11 at 17:02

1 Answers1

33

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;
user113716
  • 318,772
  • 63
  • 451
  • 440