workingxx
workingxx

Reputation: 226

Get tables row id by index

I am having some annoying trouble with this. I need to get the id of the row in my table, while searching by the index.

table_id=$(this).closest('table').attr('id'); //Table Id

I have the table id and for instance I need the second rows id. I have tried using the nth:child along with .children and other but everything I try comes back in an undefined result. I know its a simple fix but I can not seem to get it to work.

Upvotes: 1

Views: 663

Answers (2)

Adjit
Adjit

Reputation: 10305

What selector have you tried with nth-child?

If it were me, here is the selector I would use to get the ID of the second row in your table:

var table_id = $(this).closest('table').attr('id');
var t_selector = '#' + table_id + ' tr:nth-child(2)';
var row_id = $(t_selector).attr('id');

Upvotes: 0

Jamiec
Jamiec

Reputation: 136074

This is pretty simple, given the id of the table select the tr and use .eq to find the row needed - remember that it will be zero based, so the second row would be eq(1)

var table_id="myTable"
var secondRowId = $('#' + table_id + ' tr').eq(1).attr('id');
alert(secondRowId)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="myTable">
    <tr id="row1">
        <td></td>
    </tr>
    <tr id="row2">
        <td></td>
    </tr>
</table>

Upvotes: 3

Related Questions