Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude Button From Event Listener OnClick

Really simple jquery question here that I have yet to resolve. I have the following html table

<table id="table-1">
    <tr>
        <td>Value 1</td>
        <td>Value 2</td>
        <td>
            <button id="btn-1" value="Go"></button>
        </td>
    </tr>
</table>

I have the following event listener for when the table row is clicked

$("table-1 tr").on(
   'click',
    function(e){
       if(button was clicked){ 
           //do some stuff 
       } else {
           //do different stuff
       }
    }
);

I'd like this event listener to fire whenever the table row is selected, except for when the clicked item is my button. I've been trying to use :not and .not(), but no luck. Any ideas?

like image 834
Clay Banks Avatar asked Sep 11 '15 17:09

Clay Banks


2 Answers

Based off your example where you want to catch the element type.

$("#table-1 tr").on('click', function (e) {
    var elementType = $(e.target).prop('nodeName');
    if (elementType == 'BUTTON') {
        console.log('buttonClick');
    } else {
        console.log(elementType);
    };
});

http://jsfiddle.net/ymy9cn71/

like image 109
Sean Wessell Avatar answered Sep 28 '22 05:09

Sean Wessell


Use event.stopPropagation(), to prevent event bubbling to the parent elements.

$('#btn-1').click(function(event){
    event.stopPropagation();
})
like image 20
rrk Avatar answered Sep 28 '22 05:09

rrk