Okafor T Kosiso Okafor T Kosiso - 29 days ago 7
HTML Question

How to check all checkboxes according to each sub-input with jquery

I've been sweating all day about this issue, and I've not found anything online to match my need.

I have a html form with checkboxes as follows:

<input type="checkbox" name="classes[]" value="1" />JSS1 <br>
<input type="checkbox" name="subclasses[]" value="2" />Art <br>
<input type="checkbox" name="subclasses[]" value="1" />Science <br>
<input type="checkbox" name="classes[]" value="2" />JSS2 <br>
<input type="checkbox" name="subclasses[]" value="1" />A <br>
<input type="checkbox" name="subclasses[]" value="2" />B <br>


Now, I want if I check a class (let's say JSS1) all the sub-classes under JSS1 (Art, Science) will be checked and so on..

How can I do this with jquery?

Thanks for any help in advance.

Answer

Refer for fiddle. Use this:

JS:

$(document).ready(function () {
        $("input[name^='classes']").click(function () {
            if ($(this).is(':checked')) {
                $(this).siblings("input[name^='subclasses']").prop("checked", true);
            }
            else {
                $(this).siblings("input[name^='subclasses']").prop("checked", false);
            }
        });

    });

HTML:

<div>
    <input type="checkbox"  name="classes[]" value="1" />JSS1 <br>
    <input type="checkbox"  name="subclasses[]" value="2" />Art <br>
    <input type="checkbox"  name="subclasses[]" value="1" />Science <br>
</div>
<div>
    <input type="checkbox" name="classes[]" value="2" />JSS2 <br>
    <input type="checkbox" name="subclasses[]" value="1" />A <br>
    <input type="checkbox" name="subclasses[]" value="2" />B <br>
</div>