Reputation: 1477
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
Reputation:
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
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);
}
});
A few notes:
@
in your type selector but it's unnecessary$(this).parent().find
to navigate to the proper input elements in the DOM.prop('checked', false)
instead of .attr('checked', false)
.level
isn't a valid attribute. If you need custom attributes, use data-*
.Upvotes: 2