Reputation: 97
I have a table on which if I click any row it is supposed to return the row "id" number.I have used closest() function.But the issue is the closest() selects all the "tr" below it. Is there any way to limit the function to traverse only one row data.
For example my table
<tr id="0">
<td>data0</td>
</tr>
<tr id="1">
<td>data1</td>
</tr>
<tr id="2">
<td>data2</td>
</tr>
<tr id="3">
<td>data3</td>
</tr>
<tr id="4">
<td>data4</td>
</tr>
If I click the third row that is id=2, it should return only that individual id and td(data2). This is the code that I am trying as for now.
$("#myTable tr").click(function(){
trid = $(this).closest('tr').attr('id');
alert(trid);
return trid;
});
I have tried using next() or find() but I end up getting the Undefined error.Thanks.
Upvotes: 2
Views: 892
Reputation: 74738
I think you have misunderstood the concept of .closest()
. It traverses up to the parents upward, while .find()
traverses downwards to the children/grandchildren.
So as per your code it seems that you want to have the id of the clicked element. then you can just do this:
trid = this.id;
as in your code this
refers to the tr
you are clicking on.
Just noticed that you are using a global var
named trid
because it does not have the var
keyword. So if you have accidently used it then you can add var trid
like this in the above code.
Upvotes: 4
Reputation: 1207
$("#myTable tr").click(function(){
trid = $(this).attr('id');
alert(trid);
//if you want to get to the td of it
var tdVal = $(this).find('td').html();
});
Upvotes: 1
Reputation: 11750
$(document).on('click', 'td', function() {
var result = $(this).closest('tr').attr('id');
alert(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr id="0">
<td>data0</td>
</tr>
<tr id="1">
<td>data1</td>
</tr>
<tr id="2">
<td>data2</td>
</tr>
<tr id="3">
<td>data3</td>
</tr>
<tr id="4">
<td>data4</td>
</tr>
</table>
Upvotes: 1
Reputation: 7240
by clicking on tr
, you do not need to use .closest()
to access its id, just get its id using the .attr('id')
or .prop('id')
or even simply .id
as follows:
$("#myTable tr").click(function(){
trid = $(this).attr('id');
alert(trid);
});
Upvotes: 0