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