mardi 6 mars 2018

jQuery: check the parent checkbox if the child checkbox is checked

My jQuery knowledge is very rough.

I want to make a logic that if a child checkbox is checked, it checks the parent checkbox too. The input can parent, child and both:

<input type="chechkbox" name="checkbox[$counter]" class="parent" />
<input type="chechkbox" name="checkbox[$counter]" class="child" />
<input type="chechkbox" name="checkbox[$counter]" class="parent child" />

This structure:

  • 1
    • 2
    • 3
  • 4
    • 5
      • 6
      • 7

will be look like this:

<input type="chechkbox" name="checkbox[1]" class="parent" />
<input type="chechkbox" name="checkbox[2]" class="child" />
<input type="chechkbox" name="checkbox[3]" class="child" />
<input type="chechkbox" name="checkbox[4]" class="parent" />
<input type="chechkbox" name="checkbox[5]" class="child parent" />
<input type="chechkbox" name="checkbox[6]" class="child" />
<input type="chechkbox" name="checkbox[7]" class="child" />

I want if I check 3, it checks 1 and if I check 6 it checks 5 and 4, too.

Also the checkboxes are in separate table rows, becouse I want to show some information structured in table next to the checkbox.

Can you show me a script what does it? I tried this, but it's not working:

$(document).ready(function() {
    $('input.child').change(function() {
        if ($(this).is(':checked')) {
            $(this).closest('input.parent:checkbox').attr('checked', true);
        }
    });
});




Aucun commentaire:

Enregistrer un commentaire