2011-03-01 108 views
3
<div id="customerServices"> 
     <input id="s9" type="checkbox" /> Parent element<br/> 
      <input id="s15" class="parent-s9" type="checkbox" /> Child element<br/> 
      <input id="s16" class="parent-s9" type="checkbox" /> Child element<br/> 
     <br/><br/><br/> 

     <input id="s10" type="checkbox" /> Parent element2<br/> 
      <input id="s151" class="parent-s10" type="checkbox" /> Child element2<br/> 
      <input id="s161" class="parent-s10" type="checkbox" /> Child element2<br/> 
      <br/><br/><br/> 

      <input id="s101" type="checkbox" /> Parent element3<br/> 
      <input id="s102" type="checkbox" /> Parent element4<br/> 
    </div> 

頁面上有一些複選框。我需要:父母和子女複選框

  1. 檢查所有孩子是否選中父母。
  2. 如果所有孩子都未選中,請取消選中父母。
  3. 如果至少有一個孩子被選中,則檢查父代。

這是一些一些代碼,但它不工作

$('input[type=checkbox]').change(function() { 
     var id = $(this).attr('id'); 
     var children = $('.parent-' + id); 


     //Is this a child 
     if (children.length) 
     { 
      //Is it checked 
      if ($(this).is(':checked')) 
      { 
       //Find the parent 
       var className = $(this).attr('class'); 
       var pId = className.replace("parent-",""); 

       //If the parent is not checked, then check this parent 
       if (!$(pId).is(':checked')) 
        $(pId).attr('checked','checked'); 
      } 

      //Is it NOT checked 
      else{ 
       //Do other childs are not checked too? 
       //var className2 = $(this).attr('class'); 
       //$(className2) 
      } 
     } 
     //If this is a parent, then check all childs 
     esle{ 
      children.attr('checked', $(this).attr('checked')); 

     } 


    }); 

回答

5

這裏我寫的代碼給你:http://jsfiddle.net/PUWZX/4/

+0

完美!謝謝。 – Alexandre 2011-03-01 14:13:07

+0

很高興幫助:) – CoolEsh 2011-03-01 14:19:07

+1

也許簡化這樣的功能片段:'parentClicked:function(){var parentCheck = this.checked; $('#customerServices input:checkbox [class =「parent-'+ $(this).attr('id')+'」]')。each(function(){this.checked = parentCheck;}); },' – 2011-03-01 17:58:03

0

我沒有檢查所有的腳本,但首先告訴我,如果你把這個代碼放到

$(document).ready(function() { 
.... 
}); 

,如果jQuery在你的頁面上工作?

+0

是的,當然。 – Alexandre 2011-03-01 13:44:01

0

試試這個,http://jsfiddle.net/erick/dd6Qr/

// 1. Check all childs if parent is checked 
$("#s9").change(function(){ 
    if($(this).is(':checked')) { 
     var cls = '.parent-' + $(this).attr('id'); 
     $(cls).attr('checked', true); 
    } 
}); 

$('input[class*="parent"]').change(function(){ 
    var cls = '.' + $(this).attr('class') + ':checked'; 
    var len = $(cls).length; 
    var parent_id = '#' + $(this).attr('class').split('-')[1]; 

    // 3. Check parent if at least one child is checked 
    if(len) { 
     $(parent_id).attr('checked', true); 
    } else { 
     // 2. Uncheck parent if all childs are unchecked. 
     $(parent_id).attr('checked', false); 
    } 
}); 
+0

#s10,#s101,#s102呢? – Alexandre 2011-03-01 14:14:01

+0

看起來loopable?也許把它們放在一個數組中並循環。 – erickb 2011-03-01 15:40:32