0

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.

2 Answers 2

5

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/

Sign up to request clarification or add additional context in comments.

Comments

0

you could use:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.