Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the index of a row in a table using jquery

Tags:

I'm trying to find the index of a row in a table. I'm trying to use the following code, but I seem to get an index of -1.

$(document).ready(function() {     $("tr").click(function (){         var index = $("table").index($(this));         $("span").text("That was row index #" + index);     }); }); 

With html that looks like this;

<table> <tbody>     <tr><td>click</td></tr>     <tr><td>click</td></tr>     <tr><td>click</td></tr>     <tr><td>click</td></tr> </tbody> 

Thanks

like image 988
ilivewithian Avatar asked Jan 22 '09 16:01

ilivewithian


People also ask

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.

How can get row number in HTML table using jquery?

You can use the Core/index function in a given context, for example you can check the index of the TD in it's parent TR to get the column number, and you can check the TR index on the Table, to get the row number: $('td'). click(function(){ var col = $(this). parent().

How can get current TR data in jquery?

$(this). closest('tr'). children('td:eq(0)'). text();


1 Answers

Have you tried:

$("tr").index(this) 

The documentation shows just passing this and that the preceding selection should be where the node is found. If you need to find it in a specific table (and there are multiple), you may need to provide some context:

// haven't tested this $("tr", $(this).closest("table")).index(this)  
like image 52
Rob Avatar answered Sep 19 '22 22:09

Rob