Jackbd Jackbd - 4 months ago 29
jQuery Question

Find table row index that contains text JQuery

I am trying to find table row index from a link which is on the table. The code I am trying, always returning value 3. I have two many rows on my page. My code is -

Table (example) -

<table>
<tbody>
<tr>
<td>
<div>
<a herf="my link here" onclick="findindex(Rank1)">Rank1</a>
</div>
</td>
</tr>
</tbody>
</table>


JQuery -

function findindex(RName) {
var val = $('table tbody tr td div a:contains(' + RName + ')').index();
alert(val);
});


Please someone help me how to find the table row index value.

Thanks

Answer

When you call index() on that selector, you're in fact getting the index of the a element. The text selector is working fine, but after finding the element with the mached text, you need to find it's tr and get it's index:

$('table tbody tr td div a:contains("' + RName + '")').closest("tr").index();

Demo

Also, you have some syntax errors:

onclick="findindex(Rank1)" 

Should be:

onclick="findindex('Rank1')" 

Or even better:

onclick="findindex(this)" 

And the function:

function findindex(element) {
    var val = $('table tbody tr td div a:contains("' + element.innerText + '")').closest("tr").index();
    alert(element.innerText + "=" + val);
};

Demo

Note that I have added quotes to your css selector:

'table tbody tr td div a:contains("' + element.innerText + '")'
                                  ^ this                    ^ and this

To produce this result 'table tbody tr td div a:contains("Rank1")'


Now, the best thing you can do with jQuery:

Remove the onclick event attribute from your anchor elements and add a class:

<a herf="my link here" class="rank-anchor">Rank1</a>

Then bind an event on document load to your table:

$("table").on("click", "a.rank-anchor", function() {
    var index = $(this).closest("tr").index();
    alert(index);
});

In the event function, you can see that you don't need the full selector to the a element, you already have the element, so you can use this to find its tr. In this case you don't need to find the element by it's content as well, the event is being called fron it already.

Demo

Comments