tags:

views:

210

answers:

4

I'm now implementing something like this post,

the effect takes place when the row is clicked,

the problem is now:how do I know what the index of the row is inside the table?

+1  A: 

http://stackoverflow.com/questions/788225/table-row-and-column-number-in-jquery

the person who answered this question seems pretty knowledgeable. jquery apparently has an index function

http://docs.jquery.com/Core/index

Brandon H
+2  A: 

If you defined the click handler directly on the tr elements, you can use the index method like this:

$('#tableId tr').click(function () {
  var rowIndex = $('#tableId tr').index(this); //index relative to the #tableId rows
});

If the click event is bound not directly on the tr element (if you are using an anchor, a button, etc...), you should find the closest tr to get the right index:

$(selector).click(function () {
  var rowIndex = $('#tableId tr').index($(this).closest('tr'));

  return false;
});

Try an example here.

CMS
This won't work right if the page has multiple tables. Probably best to look for sibling `<tr>` elements.
TM
Shouldn't the selector of the $.index() call be restricted to the parent table of whatever TR was clicked, rather than a generic table tag?
Jonathan Sampson
@TM, @Jonathan: was a typo, restricted to a `#tableId` element
CMS
A: 

This should work:

$('#tableId tr').click(function () {
    var index = $(this).siblings('tr').index(this);
});

You don't need tr in the call to siblings if you are sure your html will be well-formed.

TM
+1  A: 

To answer your first question:

$("#id tr").click(function() {
  alert($("#id tr").index(this));
});

If you just do:

$("table tr").index(this);

and you have multiple tables on the page, you will get an erroneous result.

That being said, you don't need to know the index to move rows up and down in a table. For example:

<table id="foo">
<tr>
  <td><a href="#" class="up">Up</a> <a href="#" class="down">down</a></td>
  <td>First row</td>
</tr>
<tr>
  <td><a href="#" class="up">Up</a> <a href="#" class="down">down</a></td>
  <td>Second row</td>
</tr>
<tr>
  <td><a href="#" class="up">Up</a> <a href="#" class="down">down</a></td>
  <td>Third row</td>
</tr>
</table>

with something like:

$("a.up").click(function() {
  var row = $(this).closest("tr");
  if (row.prev().length > 0) {
    row.insertBefore(row.prev());
  }
  return false;
});
$("a.down").click(function() {
  var row = $(this).closest("tr");
  if (row.next().length > 0) {
    row.insertAfter(row.next());
  }
  return false;
});
cletus
Good point, you don't actually need the index at all.
TM