Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selecting all child checkboxes

Tags:

jquery

Firstly, just wanted to say I am hopeless with jQuery.

I was looking at some code from a post on here which selects each parent checkbox (and works):

$(function() {
  $(":checkbox").change(function () {
    $(this).parents().children(':checkbox').attr('checked', this.checked);
  });
});

We have a tree view structure using <ul> <li> and each <li> has a checkbox. I want to do the opposite of the above and perform the same checkbox selection on all child checkboxes.

Can anyone modify the above to do that?

Just to note we are using razor and each checkbox is a @Html.CheckboxFor so the output is along the lines of:

<input name="Survey.Buildings[0].IsSelected" type="checkbox" value="true" checked="checked" data-val="true" data-val-required="The Selected? field is required." id="Survey_Buildings_0__IsSelected" />
<input name="Survey.Buildings[0].IsSelected" type="hidden" value="false" />
  • EDIT 2:

OK I have fixed the HTML and the structure now looks like:

<ul>
    <li> Cbx1
        <ul>
            <li> Cbx 2 </li>
        </ul>
    </li>
    <li> Cbx3 </li>
    <li> Cbx4   
        <ul>
            <li> Cbx 5 </li>
            <li> Cbx 6 </li>
        </ul>
    </li>
</ul>

So if Cbx4 was checked Cbx5 and 6 would be checked, and if it was unchecked they would be unchecked

Much appreciated

Andy

like image 433
Andrew Rayner Avatar asked Feb 13 '13 12:02

Andrew Rayner


1 Answers

jsFiddle Demo

$(function() {
  $("input[type='checkbox']").change(function () {
    $(this).siblings('ul')
           .find("input[type='checkbox']")
           .prop('checked', this.checked);
  });
});
like image 117
nbrooks Avatar answered Oct 16 '22 20:10

nbrooks