KeVee
KeVee

Reputation: 523

Get current rowIndex of table in jQuery

My table cell gets highlighted when clicked. I need to find the rowIndex of highlighted cell. I tried doing like this

$(".ui-state-highlight").index(); // Results to 0

I tried this too...

$('td').click(function(){

    var row_index = $(this).parent().index('tr');

    var col_index = $(this).index('tr:eq('+row_index+') td');

    alert('Row # '+(row_index)+' Column # '+(col_index));

}); 
// Results : Row # -1 Column # -1

I went to through this post and tried the first answer, still couldn't get the result.

Upvotes: 41

Views: 158488

Answers (3)

Bunny
Bunny

Reputation: 87

$(this).closest("TR").index()

This one is also useful in dynamics rendering.

Upvotes: 0

Fil
Fil

Reputation: 1060

Since "$(this).parent().index();" and "$(this).parent('table').index();" don't work for me, I use this code instead:

$('td').click(function(){
   var row_index = $(this).closest("tr").index();
   var col_index = $(this).index();
});

Upvotes: 16

Adil
Adil

Reputation: 148180

Try this,

$('td').click(function(){
   var row_index = $(this).parent().index();
   var col_index = $(this).index();
});

If you need the index of table contain td then you can change it to

var row_index = $(this).parent('table').index(); 

Upvotes: 84

Related Questions