2014-06-16 3 views
0

buildTree()가 있습니다. 중첩 된 UL 내의 LI에 체크 박스를 만드는 함수입니다. 가장 바깥 쪽 UL은 div # tree 안에 싸여 있습니다.div 안에 체크 된 체크 상자가 두 개 있는지 확인하십시오.

HTML

<div id="tree"> 
    <ul> 
     <li class="speed parent-list"> 
      <input type="checkbox" name="speed" id="speed">speed<span class="glyphicon glyphicon-chevron-up"></span> 
      <ul class="speed" style="display: block;"> 
      <li class="hor_speed"><input type="checkbox" name="hor_speed" id="hor_speed">hor_speed</li> 
      <li class="ver_speed"><input type="checkbox" name="ver_speed" id="ver_speed">ver_speed</li> 
      <li class="heading"><input type="checkbox" name="heading" id="heading">heading</li> 
      </ul> 
     </li> 
     <li class="health"><input type="checkbox" name="heading" id="heading">health</li> 
     <li class="battery_level"><input type="checkbox" name="heading" id="heading">battery_level</li> 
    </ul> 
</div> 

나는 다른 모든 체크 박스가 비활성화하려면 한 번 트리 내부에 두 개의 체크 박스가 확인됩니다. 지금까지 많이 해왔지만 효과가 없습니다.

JS

buildTree(); 

var checkboxes = $('#tree [type=checkbox]'); 

checkboxes.change(function(){ 
    if(checkboxes.filter(':checked').length === 2){ 
    checkboxes.filter(':not(:checked)').prop('disabled',true); 
    } 
    else { 
    checkboxes.prop('disabled',false); 
    } 
}); 

UPDATE 내가 직접 HTML 파일의 렌더링 트리를 배치하면 코드는 완벽하게 작동하지만 일단은 jQuery를 사용하여 렌더링, 그것은 작동하지 않습니다.

+1

오늘 이전에 비슷한 질문을하지 않았습니까? 그 대답 중 하나처럼 보입니다. – Barmar

+0

일하는 것 같습니다 : [바이올린] (http://jsfiddle.net/aGVxT/) –

+0

흠, 당신이 아니 었어. Raj를 아십니까? http://stackoverflow.com/questions/24240621/disable-other-checkboxes-if-two-of-them-are-selected-using-jquery#24240710 – Barmar

답변

1

콘텐츠를 동적으로로드하는 것처럼 보입니다. 동적으로 추가 된 DOM에 이벤트를 첨부하려면 이벤트 위임이 필요합니다. 다음과 같은 질문을 던지셨습니까?

$('#tree').on('change','[type=checkbox]',function(){ 
if($('#tree [type=checkbox]').filter(':checked').length === 2){ 
    $('#tree [type=checkbox]').filter(':not(:checked)').prop('disabled',true); 
} 
else { 
    $('#tree [type=checkbox]').prop('disabled',false); 
}}); 
관련 문제