aaronstacy
aaronstacy

Reputation: 6428

Check input[type=checkbox] in jQuery event handler

I've got the following HTML:

<ul id=list>
    <li>
        <input type=checkbox />
        Item 1
    </li>
    <li>
        <input type=checkbox />
        Item 2
    </li>
    <li>
        <input type=checkbox />
        Item 3
    </li>
</ul>

And corresponding JavaScript:

$('ul').bind('click', function(e) {

    if (e.srcElement.tagName.toLowerCase() === 'input') {
        e.srcElement.checked = true;
    }

    return false;
});
    
$('body').bind('click', function() {

    alert('you should see this alert if and only if you did NOT click the list');

})

When I click a checkbox, it does not get checked. I want it to be checked when the user clicks it.

How do I make it so the checkbox is checked when the user clicks it, but still cancel the body click event handler?

I've put up a JS fiddle as well.

Edit: I understand the code is a bit clunky, but it needs to be structured this way for the application, so solutions should stay as close to the original as possible. That being said, explanations of the observed behavior would be appreciated.

Upvotes: 2

Views: 1443

Answers (3)

Birey
Birey

Reputation: 1802

  1. You are binding click to "ul" , you should be binding it to "ul> input"
  2. to avoid getting click bubbled you need to cancel bubble using event.stopPropagation() I noticed stopPropagation() should be the first thing in the function.

    $('ul').bind('click', function(e){
        e.stopPropagation();
        if (e.target.tagName.toLowerCase() === 'input') {
           e.target.checked = true;
        }
    });
    
    $('body').bind('click', function() {
    
        alert('you should see this alert if and only if you did NOT click the list');
     });
    

Upvotes: 2

aziz punjani
aziz punjani

Reputation: 25776

I think this is what you want ?

$('ul').bind('click', function(e) {          
    e.stopPropagation();       
});

$('body').bind('click', function() {
    alert('you only see this alert if and only if you did NOT click the list');
})

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816472

Use e.stopPropagation() [docs] instead of return false. The latter also prevents the default action from happening, which is toggling the state of the checkbox.

You should also consider to bind the event handler to the change event instead of click, the mouse it not the only way to toggle a checkbox. You'd still need to add an additional handler to prevent the click event from bubbling up though.

Upvotes: 3

Related Questions