Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle a TR click without the first and last TD

I have a Datatables Table with some random values in it. I would like to create a popup when the client clicks on the TR itself, but NOT on the first and the last TD of the table.

<table class="table href="#popup">
    <tr id="tr1">
        <td><input type="checkbox"></td>
        <td>Test1</td>
        <td>Test1</td>
        <td><input type="checkbox"></td>
    </tr>
    <tr id="tr2">
        <td><input type="checkbox"></td>
        <td>Test1</td>
        <td>Test1</td>
        <td><input type="checkbox"></td>
    </tr>
    <tr id="tr3">
        <td><input type="checkbox"></td>
        <td>Test1</td>
        <td>Test1</td>
        <td><input type="checkbox"></td>
    </tr>
    <tr id="tr4">
        <td><input type="checkbox"></td>
        <td>Test1</td>
        <td>Test1</td>
        <td><input type="checkbox"></td>
    </tr>
</table>

My popup plugin works like, if an href link is called and the popup div's id equals to that href value, it automatically pops up.

However if someone clicks on the first or the last TD do NOT want the popup to activate. Is it actually possible to achieve this somehow?

(The following solution should not be mentioned, because it would make the code look like a mess literally: if I select all the TD fields without the first and last, and add a href attribute to all of the selected TD elements.)

Any other suggestions are welcomed!

like image 935
Fragile Avatar asked Oct 15 '25 08:10

Fragile


2 Answers

When you click, the event is propagated from the child nodes to the parent nodes (learn more here).

You can disable event propagation in both td:first-child and td:last-child elements inside your table in order to prevent your tr event handler from being reached.

I'd also suggest you to use event delegation to keep better performance.

$('.table').on('click', 'tr', function() {
    alert('show popup'); 
});

$('.table').on('click', 'td:first-child, td:last-child', function(e) {
    e.stopPropagation();
});

FIDDLE: http://jsfiddle.net/6QTrL/1/

like image 196
Guilherme Sehn Avatar answered Oct 17 '25 01:10

Guilherme Sehn


Just use this:

Using :first-child and :last-child with not()

$('table tbody tr td').not(":first-child").not(":last-child").click(function(
   //This will only be triggered on the td that are not the first or the last on a tr

))
like image 43
Eduardo Quintana Avatar answered Oct 16 '25 23:10

Eduardo Quintana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!