Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Finding the row number of the current select element within its change handler

I have a table. In this table have select element. How can I find in which table row is select element, from within the select's event handler:

$('#selectElemID').live('change', function(){...});

Thanks

like image 991
loviji Avatar asked Mar 09 '10 16:03

loviji


People also ask

How do I get a table cell by index using jQuery?

data. find(selector); Then to find the value of different cells in a row, we'll have to specify the cell which will be done using the eq() method in jQuery. This method returns the value with a specific index number of the selected elements.

How to get index of element jQuery?

jQuery Misc index() Method The index() method returns the index position of specified elements relative to other specified elements. The elements can be specified by jQuery selectors, or a DOM element. Note: If the element is not found, index() will return -1.

How can count number of rows in jQuery?

To count the number of rows, the “#Table_Id tr” selector is used. It selects all the <tr> elements in the table. This includes the row that contains the heading of the table. The length property is used on the selected elements to get the number of rows.


2 Answers

EDIT (two years later): Please don't do it the way I previously described, it is a total waste as table rows already have a rowIndex property, so there's just no need to compute anything:

$('#selectElemID').live("change", function (){
    alert($(this).closest("tr")[0].rowIndex);
});

Demo.

<silliness>

This should do it, if you want the row number of the current select element (which is what I understand from the question):

$('#selectElemID').live('change', function(){
    alert($(this).closest("tr").prevAll("tr").length + 1);
});

To explain:

$(this).closest("tr")

means select the closest parent tr of this select element.

.prevAll("tr").length + 1

means select all the previous rows, and get me the length of the returned collection. Increment it by one to get the current row number, because we are at total previous rows + 1.

For more information:

  • http://api.jquery.com/prevAll/
  • http://api.jquery.com/closest/

</silliness>

like image 69
karim79 Avatar answered Nov 06 '22 11:11

karim79


also:

$('#selectElemID').live('change', function(){
    alert($(this).closest("tr")[0].rowIndex);
});
like image 2
BbErSeRkK Avatar answered Nov 06 '22 11:11

BbErSeRkK