3

I am trying to allow folding and unfolding of a nested list by either clicking the li or the input type=[checkbox] adjacent to the li. But checking the checkbox causes firing of the container li causing the parent li to fold.

Easier explained by this fiddle

I solved it by setting a global

window.checkbox_checked = true

show in this fiddle but I'de rather not use a global. Is there a cleaner way of doing this? I tried using event.stopImmediatePropagation() and event.stopPropagation() but neither worked for me?

Thanks

Update

As pointed out by Felix King, my problem was wrapping my li in a div, which disabled event.stopPropagation() solution

Community
  • 1
  • 1
david_adler
  • 9,690
  • 6
  • 57
  • 97
  • *"I tried using `event.stopImmediatePropagation()` and `event.stopPropagation()` but neither worked for me?"* Maybe you are not using it *correctly*? Please post the corresponding code. – Felix Kling Nov 24 '13 at 17:23
  • NVM, I just had a look at your HTML. It's completely invalid. A `div` element cannot be the child of a `ul` element. The text and the `input` element have to be children of the `li` element which has to be a child of the `ul` element. Then `stopPropagation` should work as expected. – Felix Kling Nov 24 '13 at 17:26
  • @FelixKling yeah true, but then i lose the formatting! ideally the input would be on the left. – david_adler Nov 24 '13 at 17:39
  • 1
    Easily done: http://jsfiddle.net/QwNYh/5/. – Felix Kling Nov 24 '13 at 17:40

1 Answers1

1

Just check the node name inside the click handler if it is an UL then just skip that particular click event.

event.target.nodeName

Code:

$('li.expandable').on('click', function (e) {

if(e.target.nodeName !== "INPUT")
{
    //Code goes here.
}
});

DEMONSTRATION

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130