Sylnois
Sylnois

Reputation: 1631

Check if last element was clicked

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

Answers (4)

Ibrahim Khan
Ibrahim Khan

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

Tushar
Tushar

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

Demo

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

Demo

Upvotes: 1

Beep
Beep

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

JSFiddle

Upvotes: 1

vcanales
vcanales

Reputation: 1828

You don't need that .find(). Also, do you want to check if the last tdor las tr was clicked? Either way, you just have to do it like this:

$('table').on('click', 'td', function(e) {
    if($(this).is(':last-child')){
        alert("Last td clicked!");
    }
});

DEMO

Upvotes: 2

Related Questions