mesnicka
mesnicka

Reputation: 2548

jQuery index method

i know there is a lot of info about index() in jQuery. But my case is complicate and I need help.

<table>
 <tbody>
  <tr>
   <td>abc</td>
   <td><input type="checkbox"/></td>
  </tr>
  <tr>
   <td>def</td>
   <td><input type="checkbox"/></td>
  </tr>
 </tbody>
</table>
<table>
 <tbody>
  <tr>
   <td>ghi</td>
   <td><input type="checkbox"/></td>
  </tr>
  <tr>
   <td>jkl</td>
   <td><input type="checkbox"/></td>
  </tr>
 </tbody>
</table>

What i need is index of "tr" element in current "tbody" where i've just checked the box.

Upvotes: 0

Views: 235

Answers (2)

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76870

you could use:

$('input').click(function(){
    var i = $(this).closest('tr').index();
    //i is the index
});

Upvotes: 0

user113716
user113716

Reputation: 322452

If your code is in a handler, do this:

$('table input[type="checkbox"]').change( function() {
    var idx = $(this).closest('tr').index();
});

Example: http://jsfiddle.net/bA9dx/


Or if you're saying you need to index of the row from among all the rows in the table, do this:

var rows = $('table tr');

$('table input[type="checkbox"]').change( function() {
    var idx = rows.index( $(this).closest('tr') );

    alert( idx );
});

Example: http://jsfiddle.net/bA9dx/1/

Upvotes: 5

Related Questions