Reputation: 13308
I need to check all child checkboxes when a user check one parent checkbox. For example, if a user checks the checkbox with id ='s9'
then checkboxes with id s15
, s16
and s116
must be checked, because they have parentId='s9'
.
<span class='font-bold'><input id='s1' type='checkbox'/>bla</span><br/>
<span class='left-indent'><input id='s2' parentId='s1' type='checkbox'/>bla11</span><br/>
<span class='left-indent'><input id='s3' parentId='s1' type='checkbox'/>bla12><br/>
<span class='left-indent'><input id='s4' parentId='s1' type='checkbox'/>bla13</span><br/>
<span class='left-indent'><input id='s5' parentId='s1' type='checkbox'/>bla14</span><br/>
<span class='left-indent'><input id='s6' parentId='s1' type='checkbox'/>bla15</span><br/>
<span class='font-bold'><input id='s8' type='checkbox'/>bla2</span><br/>
<span class='font-bold'><input id='s9' type='checkbox'/>bla3</span><br/>
<span class='left-indent'><input id='s15' parentId='s9' type='checkbox'/>bla31</span><br/>
<span class='left-indent'><input id='s16' parentId='s9' type='checkbox'/>bla32</span><br/>
<span class='left-indent'><input id='s116' parentId='s9' type='checkbox'/>bla32</span><br/>
<span class='font-bold'><input id='s10' type='checkbox'/>bla4</span><br/>
<span class='font-bold'><input id='s11' type='checkbox'/>bla5</span><br/>
UPDATE
If some child are checked, parent must be checked too.
If all childs are unchecked, parent must be unchecked too.
Upvotes: 1
Views: 3776
Reputation: 83163
You shouldn't use parentId
as a custom attribute as it will invalidate your HTML. Use classnames instead:
<input id="s9" type="checkbox" />
<input id="s15" class="parent-s9" type="checkbox" />
<input id="s16" class="parent-s9" type="checkbox" />
Example:
$('input[type=checkbox]').change(function() {
// get id of the current clicked element
var id = $(this).attr('id');
// find elements with classname 'parent-<id>' and (un)check them
var children = $('.parent-' + id).attr('checked', $(this).attr('checked'));
});
Upvotes: 4