16

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.

7
  • Well, one problem is that you need to nest <td> tags inside <tr> tags. I don't think it is legal to put them directly in a <tbody> tag. Commented Jun 24, 2011 at 16:39
  • They are I just forgot to add them in the question example...it is Friday. : D I edited it. Commented Jun 24, 2011 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. Commented Jun 24, 2011 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. Commented Jun 24, 2011 at 16:48
  • Got it working: var colIndex = row.children().index($(this).parent()); was omitting the $ Commented Jun 24, 2011 at 16:55

1 Answer 1

34

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that's more elegant than what i am doing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.