Reputation: 10039
I'd like to automatically uncheck or check children's checkboxes:
HTML:
<ul>
<li>1 <input type='checkbox' /></li>
<ul>
<li>1.1 <input type='checkbox'' /></li>
</ul>
<ul>
<li>1.1.1 <input type='checkbox' /></li>
</ul>
</ul>
Javascript:
$('li input').change(function(){
if($(this).is(":checked")){
$(this).parent().next().children("li").children("input").attr("checked", true);
console.log("checked")
}else{
$(this).parent().next().children("li").children("input").attr("checked", false);
console.log("not checked")
}
})
But it only works for the first occurence. I don't understand why because the 1.1 change and the event change is not triggered
Thanks
Upvotes: 0
Views: 1608
Reputation: 144719
You can use closest method:
$('ul input').change(function(){
var $this = $(this).closest('ul');
$this.add($this.nextAll()).find("input").prop("checked", this.checked);
})
Note that your markup need modofication why not using li
elements?
<ul>
<li>1 <input type='checkbox' /></li>
<li>1.1<input type='checkbox' /></li>
<li>1.1.1 <input type='checkbox' /></li>
</ul>
$('ul input').change(function(){
$(this).parent().nextAll().find("input").prop("checked", this.checked);
})
Upvotes: 1
Reputation: 253446
If you correct your HTML, to the following:
<ul>
<li>1 <input type="checkbox" />
<ul>
<li>1.1 <input type="checkbox" />
<ul>
<li>1.1.1 <input type="checkbox" /></li>
</ul>
</li>
</ul>
</li>
</ul>
Then the following jQuery works:
$('input:checkbox').change(
function(){
var state = this.checked ? true : false;
$(this).next('ul').find('input:checkbox').prop('checked', state);
});
The problems with your HTML are that a ul
element is not a valid child of another ul
, or ol
, element. The only valid children of ul
(and ol
) is the li
element, everything else is invalid, unless it's contained within an li
.
References:
Upvotes: 1
Reputation: 324760
For the first checkbox, "parent" is the <li>
that's in the outer <ul>
. For the others, their "parent" is the <li>
that's isolated in another <ul>
and has no "next".
Upvotes: 0