"Checkbox1
   Checkbox2A
   Checkbox2B
     Checkbox2AA --- hidden at first
     Checkbox2AB --- hidden at first"

How will I implement this using javascript/jquery? When Checkbox1 is checked, Checkbox2A and Checkbox2B will also be checked. When Checkbox2A is checked, Checkbox2AA and Checkbox 2AB will be visible.

Member Avatar

diafol

Your logic doesn't make sense or does it? Checking chk1 will check everything. Why does 2a check 2aa and 2ab? From the layout it seems that 2b should control them.

Hi ethan,

Though not the same as your request, you can do it through css alone. Having this kind of html structure:

<div class="checkBox">
    1
    <input type="checkbox" />
    <div>
        1.1
        <input type="checkbox" />
        1.2
        <input type="checkbox" />
        <div>
            1.2.1
            <input type="checkbox" />
        </div>
    </div>
    2
    <input type="checkbox" />
    <div>
        2.1
        <input type="checkbox" />
        2.2
        <input type="checkbox" />
        <div>
            2.2.1
            <input type="checkbox" />
        </div>
    </div>
</div>

And this css rules.

div {
    display: none;
}

.checkBox {
    display: block;
}

input[type*="checkbox"]:checked ~ div:first-of-type {
    display:block;
}

You can implement the same thing as what I think you want without JS.

But if you still want to push through for a JS implementaion. Using the same HTML Structure, use this in your js:

$(function(){
    $("input[type*='checkbox']").on({
        click: function(){
                $(this).next("div").toggle();
        }
    })
});

and this css rule:

div {
    display: none;
}

.checkBox {
    display: block;
}

You can also see my sample in these fiddles below:

CSS IMPLEMENTATION: CSS Sample
jQuery IMPLEMENTATION: jQuery Sample