Getting column number from td
Asked Answered
M

2

10

Writing an extension for tablesorter.. though its my first attempt at extending any js. I have a number of <select>s within a row of <td>s & need to know the column this td sits in.

When a value is changed in any of these selects e.g.

$('select').change(function(){

});

I need to get hold of the column this select is sitting in to set col for:

('tr.result > td:nth-child('+col+')').each(function(){

Is there a way I can get this from the td select is in?!?

-- solution for my specific problem was:

$('select').change(function(){

    td  = $(this).parent('td');

    col = $(td).parent().children().index(td);

});
Macknair answered 15/2, 2011 at 13:20 Comment(1)
Documentation: api.jquery.com/indexHomogenize
P
12

You can use the index() function.

col = $(this).parent().children().index($(this));
Polyphony answered 15/2, 2011 at 13:23 Comment(4)
Thanks- look about right, but i've tried a few variants on this, and all are returning -1. The only issue I can think of is that the table divides into <thead> & <tbody> but altering: .children('tbody'). doesnt help?Macknair
Yup you're right, of course you need the children of the parent (TR, not TBODY or TABLE)... see updatedPolyphony
Oh & just noticed the one other problem was that the 'this' in my question was select so solution is a slight variant. Thanks for the help :)Macknair
You're welcome, glad to hear you know what's going on instead of just blindly copying the answer ;)Polyphony
Q
6

The cellIndex property returns the position of a cell in the cells collection of a table row. w3schools

 td.cellIndex 

demo

Quadrant answered 25/2, 2014 at 9:32 Comment(1)
cellIndex is broken for tables using colspan. This means cellIndex might return different values for cells being on top of each other.Luffa

© 2022 - 2024 — McMap. All rights reserved.