Find Table Row Index using jQuery

superachu picture superachu · Oct 25, 2009 · Viewed 69k times · Source

I'm an intermediate user in jQuery. I know to find the rowIndex of a table using jQUery, but my scenario is a different one. My table(GridView) consists of 20 columns and each column with different controls like textbox, dropdownlist, image, label. All are server side controls in each row. I bind the gridview with the records from the database. Now when I click on any control or onchange of any textbox, I need to get the rowIndex of that changed column's row. Here is the code I've user:

$("#gv1 tr input[name $= 'txtName']").live('click', function(e){
   alert($(this).closest('td').parent().attr('sectionRowIndex'));
});

But I'm unable to get the rowIndex. If I use any html control inside the gridview, I'm able to get the rowIndex. Is there any way to find out the rowIndex when a server control inside the gridview is clicked?

Answer

Darin Dimitrov picture Darin Dimitrov · Oct 25, 2009

Try this:

var rowIndex = $(this)
    .closest('tr') // Get the closest tr parent element
    .prevAll() // Find all sibling elements in front of it
    .length; // Get their count