Ebbs
Ebbs

Reputation: 1050

Can't stop propagation of event in Jquery

I'm a bit confused. I have list of what are names with a checkbox next to them. The list is constructed dynamically in after doing a post to the backend.

Problem is whenever I click on the checkbox it immediately gets unchecked. The reason I know this is that if an alert is inserted in the event, the checkbox is actually checked, until the alert is dismissed.

This is my code:

$("#NamesList").on("click", "input[type='checkbox']", function (e) {
    CheckboxClicked();
    return false;
})
.on("click", "li", function (e) {
    e.preventDefault();
    e.stopPropagation();

    switch (e.target.nodeName) {
         case "A":
             GetPerson(e.target.href)
             break;
         case "LI":
              GetPerson($("a", e.target).attr("href"))
              break;
         default: return false;
     }

     return false;
});

Thing is, I have link in the listitem that I need to be able to follow. If the part for navigating to the link is taken out, the checkbox functionality works fine.

This is what a typical list of names look like:

<ul id="NamesList">
     <li id="1">
         <input class="checkbox" type="checkbox" />
         <a href="/some/link/somewhere/1">John Smith</a>
     </li>
</ul>

Any ideas?

Upvotes: 0

Views: 1174

Answers (2)

Hans Roerdinkholder
Hans Roerdinkholder

Reputation: 3000

$("#NamesList").on("click", "input[type='checkbox']", function (e) {
    CheckboxClicked();
    e.stopPropagation();
})

replaced return false; with e.stopPropagation();. return false is equivalent to e.preventDefault(); e.stopPropagation(); However, you don't want to prevent the default :)

Working fiddle: http://jsfiddle.net/wpx6A/

Upvotes: 7

Anto Subash
Anto Subash

Reputation: 3215

try

e.stopImmediatePropagation()

this will make sure the event is not propagated.

Upvotes: 4

Related Questions