Find Table Row Index using jQuery

你离开我真会死。 提交于 2019-12-18 19:11:15

问题


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?


回答1:


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



回答2:


sectionRowIndex is a property of the <tr> element, not an attribute.

The correct way to modify your sample code is to access the jQuery item with a zero indexer like this:

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

This will return the correct row index for you. Also, if you are going to use jQuery's .closest() function to traverse up the DOM and also .parent(), why not compine those two and just traverse up to the closest <tr> element?

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

This will also handle weird cases where the parent->child relationship isn't exactly what you expected. For example if you chained a $(this).parent().parent() and then decided to wrap your inner cell with another div or span, you might screw up the relationship. The .closest() is the easy way out to make sure it will always work.

Of course my code samples are re-using your provided sample above. You may wish to test with a simpler selector first to prove it works, then refine your selectors.




回答3:


This is for a checkbox in the table cell, on change:

 var row = $(this).parent().parent();
 var rowIndex = $(row[0].rowIndex);
 console.log(rowIndex);



回答4:


Should be able to just use:

var rowIndex = $(this).parents("tr:first")[0].rowIndex;


来源:https://stackoverflow.com/questions/1620391/find-table-row-index-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!