tags:

views:

362

answers:

2

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

A: 

Try:

var index = $("table tr").index($(this));

The documentation for index() says:

Searches every matched element for the object and returns the index of the element, if found, starting with zero. If a jQuery object is passed, only the first element is checked.

You need to call the index() on a collection of <tr> elements, not the parent <table>.

Ates Goral
+3  A: 

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).parent("table")).index(this)
Rob
Thanks, that's very helpful.
ilivewithian