Reputation: 1631
I am trying to find out if the last td
of an tr
was clicked. This is my HTML example:
<table>
<tr>
<td>Foo</td>
<td>Bar</td>
<td>Clicked</td>
</tr>
</table>
And this is my currently javascript code (not working like that):
$('table').on('click', 'tr', function(e) {
if ($(this).find('td').is(':last-child')){
alert("Last td clicked!");
}
});
Note: I need to use the tr-selector
for other purpose. So it it important, that the on click refers to the tr
.
Upvotes: 2
Views: 2894
Reputation: 20750
Try like following using tr td:last-child
selector.
$('table').on('click', 'tr td:last-child', function (e) {
alert("Last td clicked!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Foo</td>
<td>Bar</td>
<td>Clicked</td>
</tr>
</table>
UPDATE: as per updated question
$('table').on('click', 'tr', function (e) {
if($(e.target).is(':last-child')) {
alert("Last td clicked!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Foo</td>
<td>Bar</td>
<td>Clicked</td>
</tr>
</table>
Upvotes: 3
Reputation: 87233
This answer assumes that the event hander is common to all the <td>
elements and want to distinguish between the last element
Without changing the event handler:
The event object holds the reference of the element that was clicked. This can be used.
The target
property in the event
object contains the reference of the element that is actually clicked. jQuery is()
can be used to check if the element is the last in the <tr>
.
$('table').on('click', 'tr', function(e) {
console.log($(e.target).is($(this).find('td:last')));
// OR
// console.log($(e.target).is(':last-child'));
});
Binding event on <td>
The event can be bind on the <td>
elements inside the <table>
and :last-child
selector can be used with is()
to check if the element that is clicked is the last child.
$('table tr').on('click', 'td', function(e) {
console.log($(this).is(':last-child'));
});
Upvotes: 1
Reputation: 122
Add the event listener directly to the last child
Html
<table>
<tr>
<td>Foo</td>
<td>Bar</td>
<td>Clicked</td>
</tr>
</table>
Javascript
$('table').on('click', 'tr td:last-child', function(e) {
alert("Last td clicked!");
});
Upvotes: 1