How to handle click on <tr> but not on child elements?

I am handling the click with the following code.

Entry table

<table>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
    </tr>
</table>
      

Click handler

$('table tr').click(function(){
    alert('clicked');
});​

      

http://jsfiddle.net/n96eW/

It works well, but if I have a checkbox in the td, it handles it when clicked as well.

Is there a way to handle the TR click but not activate the children?

+3


source to share


3 answers


http://jsfiddle.net/n96eW/1/

Add another event handler to your checkbox to stop scrolling:



$('table tr').click(function(){
    alert('clicked');
});

$('table tr input').click(function(e) {
    e.stopPropagation();
});

      

+13


source


You can check event.target

for event filtering:



$('table tr').click(function(e){
    if(e.target.tagName.toLowerCase() != "input") {
        alert('clicked');
    }
});​

      

+4


source


You can also use

$("tr").on('click',function() {

  if (!$(event.target).is('input'))
    alert('clicked');

});

      

+1


source







All Articles