views:

39

answers:

3

I have this (simplification):

$(li).click(function{alert("test");});

<li>
   <input>
</li>

What's the best way to bind an event to li but not fire when the user clicks on the input element?

+2  A: 

One solution could involve using event.target.

In the event handler, use

if( $(event.target).is('input') )
    return;
Stefan Kendall
+2  A: 

I think you'll have to manually filter it.

$(li).click(function(e) {
    if ($(e.target).is("input")) {
        alert("Test");
    }
});
ChaosPandion
+5  A: 

Try using the stopPropagation method on the Event object.

$('input').click(function(event) {
    event.stopPropagation();
});

You could also target specific children (or direct children) of li using a combination of selectors:

$('li > input, li strong, li span').click( ... );
Matt Huggins
+1 The only good answer to this question!
Mathias Bynens
I knew my solution was bad ;)
Stefan Kendall