[eluser]Bramme[/eluser]
Hey all
I have a two dimensional unordered list on my website that lists a navigation: main elements in the first list and their subpages in sublists.
Each page has a checkbox that's used to enable/disable certain pages for certain users. When you're not allowed to visit the subpages of an item, it offcourse doesn't make sense to put that item in the nav in the first place, so for usability's sake, I wanted some javascript that handled the checkboxes as follows:
When you select/deselect a main item all subitems get automatically selected/deselected as well. When you deselect/select all subitems of one category, the main category get's deselected/selected too. One last thing: when all is deselected, and you select a subitem, the main item has to get checked too.
Now I whipped up some jQuery that actually works, but I was wondering if there's any better way of doing this... My second function looks too complicated, but I'm afraid I don't know jQuery well enough...
Here's my code:
Code:
$(document).ready( function () {
$("#restrictions > li > input").click(function() {
var children = $(this).parent().children("ul").children("li").children("input");
children.attr("checked", $(this).attr("checked"));
});
$("#restrictions li ul li input").click(function() {
var inputs = $(this).parent().parent().find("input");
var prev = '';
var changed = false;
inputs.each(function(i) {
if (prev == '') {
prev = $(this).attr("checked");
}
if (prev != $(this).attr("checked")) {
changed = true;
}
prev = $(this).attr("checked");
});
if(!changed) {
$(this).parent().parent().parent().children("input").attr("checked", prev);
}
if($(this).attr("checked") == true) {
$(this).parent().parent().parent().children("input").attr("checked", true);
}
});
});
changed the code to this
Code:
$(document).ready( function () {
$("#restrictions input").click(function() {
if($(this).is("#restrictions > li > input")) {
// we clicked on a parent, set all children to same state
$(this).parent().find("input").attr("checked", $(this).attr("checked"));
} else {
// we clicked on a child, time to set the parent.
var siblings = $(this).parent().siblings().children("input");
var parent = $(this).parents("li:not(:first)").children("input");
if($(this).is(":checked")) {
// checked so check parent
parent.attr("checked", true);
} else {
// unchecked, so check siblings first before unchecking parent
if(siblings.filter(":checked").length == 0) {
parent.attr("checked", false);
}
}
}
});
});
Any JS/jQuery gurus got any remarks?