Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 605
KeVee Avatar asked Oct 31 '12 06:10

KeVee


People also ask

How do I get current rowIndex of a table using JavaScript?

var index = $('table tr'). index(tr); If no JQuery used, you can loop through all the TR element to find the matched TR.

How do you find the index of an element in a table in JavaScript?

JavaScript Array findIndex() The findIndex() method executes a function for each array element. The findIndex() method returns the index (position) of the first element that passes a test. The findIndex() method returns -1 if no match is found.


2 Answers

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();  
like image 107
Adil Avatar answered Sep 27 '22 23:09

Adil


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(); }); 
like image 37
Fil Avatar answered Sep 28 '22 00:09

Fil