user198729
user198729

Reputation: 63676

How to know index of a <tr> inside a <table> with jQuery?

I'm now implementing something like this post (specifically, the effect takes place when the row is clicked)

How do I know what the index of the row is inside the table?

Upvotes: 15

Views: 47221

Answers (4)

sn3p
sn3p

Reputation: 746

How about HTMLTableRowElement.rowIndex?

The HTMLTableRowElement.rowIndex read-only property represents the position of a row in relation to the whole <table>.

Beware that if you have thead, tbody or tfoot tags wrapping the rows, these will be counted as well.

$("table tr").click(function () {
  console.log(this.rowIndex);
});

Upvotes: 0

cletus
cletus

Reputation: 625237

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;
});

Upvotes: 1

TM.
TM.

Reputation: 111077

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.

Upvotes: 1

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827724

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.

Upvotes: 29

Related Questions