I have a country list. It’s splitted up 3 times.
[ ] World
[ ] Africa
[ ] Congo
[ ] Europe
[ ] Netherlands, the
[ ] Italy
now if I click world, I want all of them to be checked.
If I click Africa, I only want Congo to be checked.
If I click Europe, Both Italy and Netherlands, the should be checked.
If I click Netherlands, the, and Italy, Europe should be checked, and the same should happen with World when clicking Europe and Africa.
I came up with the following jquery script for it:
$(function() {
$(":checkbox").click(function() {
var maxlevel = 3;
var level = $(this).attr("class").substring(5, 6);
var level_checked = $(this).attr("checked");
//update children
$('input', $(this).parent('div')).each(function() {
var curlevel = $(this).attr("class").substring(5, 6);
if (curlevel > level) {
$(this).attr("checked", level_checked);
}
});
//update parents?
});
});
I am using the following html code:
<div>
<input class="layer1" type="checkbox" />Layer1 <br />
<div>
<input class="layer2" type="checkbox" />Layer2 <br />
<div>
<input class="layer3" type="checkbox" />Layer3 <br />
<input class="layer3" type="checkbox" />Layer3 <br />
</div>
</div>
<div>
<input class="layer2" type="checkbox" />Layer2 <br />
<div>
<input class="layer3" type="checkbox" />Layer3 <br />
<input class="layer3" type="checkbox" />Layer3 <br />
</div>
</div>
</div>
Updating the children when clicking something works, but updating the parents when clicking a box.. I have no idea how to get that done. I found 2 pieces of code that did this, but they only worked for 1 ‘subgroup’ of checkboxes, and not for 2 like in my case.
Can anyone help me out here?
Welcome to algorithms class. Here’s the basic format:
Write the question down, as something which can be answered. This is step 1.
Step 2, write the answer down as a series of steps, and make each step as detailed as reasonable.
Step 3, convert each specific step into either code or pseudocode (repeating step 3 to convert pseudocode to code).
Congratulations, you’ve now implemented an algorithm in code. So for your specific question, I’ll do the first two steps, and let you do the third:
How do I check all of the parent checkboxes of a given checkbox when it gets clicked?
How do I check all of the sibling checkboxes to determine their state?
Note that there are faster/easier inline methods for determining the answer to #2, but depending on how you abstract it, that is an easy method to implement and only requires upkeep in one place.
I don’t doubt that when you posted this question you were hoping for an easy answer, and while there are some shortcuts, this is the simplest way (and simplest is always most maintainable) so do it the simplest way for now. When you have specific code that you want to optimize that can be done later.
If you do as I helped you here, and write the long code, you’ll be able to accomplish what you want.