Redbox
Redbox

Reputation: 1477

JQuery: uncheck subchild checkbox inside ul li

i have a code like this:

 <ul>  
     <li><input type="checkbox" level="child"  name="somename1" value="1" /> Child 1</li>
     <li><input type="checkbox" level="child"  name="somename2" value="2" /> Child 2 <br />
            <ul>
                <li><input type="checkbox" level="subchild" name="somename1" value="3" />Sub Child 1</li>
                <li><input type="checkbox" level="subchild" name="somename2" value="3" />Sub Child 2</li>
            </ul>
     </li>
     <li ><input type="checkbox" level="child"  name="somename3" value="3" /> Child 3</li>
 </ul>

and jquery code:

$('input[@type=checkbox][level="child"]').click(function (event) {
        var checked = $(this).is(':checked');
        if (checked) {
          alert("checked");
        } else { //for click child to uncheck subchild
            alert("when unchecked");
            $(this).closest('ul > li').children('input[@type=checkbox][level="subchild"]').attr('checked', false);

        }
});

Situation: child 2 + subchild1 + subchild2 is checked

Problem: i want to uncheck the subchild1 + subchild2 when i clicked uncheck of child 2, my code above does not work. i think it has something to do with:

$(this).closest('ul > li').children('input[@type=checkbox [level="subchild"]').attr('checked', false);

any help would be great. Here is JSfiddle: http://jsfiddle.net/p324w/

Upvotes: 1

Views: 5255

Answers (2)

user1823761
user1823761

Reputation:

Working FIDDLE Demo

Try this:

$('input[type=checkbox][level="child"]').on('click', function () {
    // get checked status
    var checked = $(this).is(':checked');

    // go up the dom to the parent of checkbox (li)
    $(this).closest('li')

        // find all subchild checkboxes
        .find('input[type=checkbox][level="subchild"]')

        // make them as the parent checkbox (checked or not)
        .prop('checked', checked);
});

Upvotes: 1

j08691
j08691

Reputation: 207963

$('input[type=checkbox][level="child"]').click(function (event) {
        var checked = $(this).is(':checked');
        if (checked) {
          console.log("checked");
        } else { //for click child to uncheck subchild
            $(this).parent().find('input[type=checkbox][level="subchild"]').prop('checked', false);
        }
});

jsFiddle example

A few notes:

  • I'm not sure why you were using @ in your type selector but it's unnecessary
  • You need to use $(this).parent().find to navigate to the proper input elements in the DOM
  • Use .prop('checked', false) instead of .attr('checked', false).
  • level isn't a valid attribute. If you need custom attributes, use data-*.

Upvotes: 2

Related Questions