2011-03-01 97 views
1

當用戶選中一個父複選框時,我需要檢查所有子複選框。例如,如果用戶選中複選框id ='s9',則必須選中編號爲s15s16s116的複選框,因爲它們的編號爲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/> 

更新

如果一些孩子進行檢查,父母也必須被檢查。

如果所有孩子都未選中,父母也必須不加選中。

回答

4

您不應該使用parentId作爲自定義屬性,因爲它會使您的HTML無效。使用類名代替:

<input id="s9" type="checkbox" /> 
<input id="s15" class="parent-s9" type="checkbox" /> 
<input id="s16" class="parent-s9" type="checkbox" /> 

實施例:

$('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')); 
}); 

Live example here.

+0

1變種ID = this.id; (只是一個選項) – benhowdle89 2011-03-01 10:01:05

+0

請看看我的更新。 – Alexandre 2011-03-01 12:12:08

+0

@Alex,我給你一個指針,現在*去寫一些代碼* :)如果你不能得到它的工作,發佈一個新的問題,說明問題和你已經嘗試過。如果我只是向您提供代碼,那沒有意義。 – 2011-03-01 12:38:24