2011-06-13 3 views
0

이 중첩 목록 구조가 있습니다. 내 나무는 n 레벨까지 갈 수 있습니다.JQuery에서 직접적인 부모 확인란을 모두 확인하십시오.

자식이 선택되어있는 경우에만 부모를 선택할 수있는 JQuery 선택기가 필요합니다.

<ul id="treeFeatureList"> 
<li> 
    <input type="checkbox" name="selectedRole"> 
    Application Manager 
    <ul> 
     <li> 
      <input type="checkbox" name="selectedRole"> 
      Application Manager Panel 
     </li> 
     <li> 
      <input type="checkbox" name="selectedRole"> 
      Client Role 
      <ul> 
       <li> 
        <input type="checkbox" name="selectedRole"> 
        Client Task 1 
       </li> 
       <li> 
        <input type="checkbox" name="selectedRole"> 
        Client Task 2 
       </li> 
      </ul> 
     </li> 
    </ul> 
</li> 
</ul> 

내가 원하는 것은 : 클라이언트 작업 1 또는 Task2를 선택하면는, 클라이언트 역할 및 응용 프로그램 관리자가 너무 확인되었다. 확실히 응용 프로그램 관리자 패널이 아닙니다 (선택되지 않은 채로 있어야합니다).

이 마법의 선택자를 만드는 것이 좋습니다.

답변

1
$('input[type="checkbox"]').change(function() { 
    if ($(this).is(':checked')) { 
     $(this).parents('ul').siblings('input:checkbox').attr('checked', true); 
    } 
    else 
    { 
     $(this).parents('ul').siblings('input:checkbox').attr('checked', false); 
    } 
}); 

Here 데모입니다.

1

.closest().siblings()의 조합으로 원하는 것을 얻을 수 있습니다. "부모"체크 박스가있는 형제 인 체크 입력의 가장 가까운 조상을 선택한 다음 해당 체크 박스를 탐색하려고합니다. 코드는 다음과 같을 것이다 :

$('input:checkbox').change(function() { 
    //if you are using < jQuery 1.6, use .attr() instead of .prop() 
    if (this.checked) { 
     $(this).closest('ul').siblings('input:checkbox').prop('checked', true); 
    } 
}); 

Here is a live demo ->

0
$('input[type="checkbox"]').change(function() { 
if ($(this).is(':checked')) { 
    $(this).parents('ul').siblings('input:checkbox').attr('checked', true); 
} else { 
     //if any of the sibling is checked, do not uncheck the main category 
     var isSiblingChecked = false; 
     $(this).parent().siblings().each(function() { 
      if (($(this).find('input[type="checkbox"]').is(':checked'))) { 
       isSiblingChecked = true; 
      } 
     });  
     if (isSiblingChecked == false) {    
    $(this).parents('ul').siblings('input:checkbox').attr('checked', false); 
     } 
} 
}); 
관련 문제