2014-01-15 2 views
0

체크 박스를 체크/체크하지 않으려 고 모든 체크 박스를 체크/체크하지 않으려 고합니다.두 개의 다른 클래스로 모든 체크 박스를 확인하는 방법

HTML :

<th><input type="checkbox" name="pay" id="chkAll" class="chkAll"/>With Pay</th> 
<th><input type="checkbox" name="pay" id="chkAll2" class="chkAll2"/>Without Pay</th>  


<td><input type="checkbox" name="pay" value="With Pay" class="chk" id="chk"/></td> 
<td><input type="checkbox" name="pay" value="Without Pay" class="chk2" id="chk2"/></td> 

JS : 여기

내 코드입니다

$('.chkAll').change(function() { 
    var id = $(this).attr("id").replace("check_", ""); 
    if ($(this).is(':checked')) { 
     $(".chk").prop('checked', true); 
     $(".chk2").prop('checked', false); 
     $('.chkAll2').prop('checked', false); 
    } else { 
     $(".chk").prop('checked', false); 
    } 
}); 

$('.chkAll2').change(function() { 
    var id = $(this).attr("id").replace("check_", ""); 
    if ($(this).is(':checked')) { 
     $(".chk2").prop('checked', true); 
     $(".chk").prop('checked', false); 
     $('.chkAll').prop('checked', false); 
    } else { 
     $(".chk2").prop('checked', false); 
    } 
}); 

$('.chk').not('[id^=chkAll]').change(function() { 
    if ($(this).is(':checked')) { 
     $('.chkAll').prop('checked', true); 
    } else { 
     $('.chkAll').prop('checked', false); 
    } 
}); 
+0

다음에 대한 간단한 jQuery 코드

$(document).ready(function(){ $('.chk-all').on('change', function(){ $('.' + $(this).data('child')).prop('checked',this.checked); }); }); 

에게있다' 클래스 '라고합니다. –

답변

1

을 시도해보십시오

jQuery(function() { 

    function checkAll($all, $els) { 
     $all.change(function() { 
      $els.prop('checked', this.checked); 
     }); 
     $els.change(function() { 
      $all.prop('checked', $els.not(':checked').length == 0); 
     }); 
    } 

    checkAll($('#chkAll'), $('.chk')) 
    checkAll($('#chkAll2'), $('.chk2')) 
}) 

데모 : Fiddle

여기에
+0

감사합니다 :) 나는 마지막 질문이 하나 있습니다. 지불하지 않고 모두 체크 한 경우 지불하지 않고 지불 체크 박스를 체크하면 은 지불하지 않고 – user3189194

+0

@ user3189194 미안하지만 ..... ..... 다시 설명 할 수 있습니까? –

+0

td를 확인하는 동안 "withpay") 지불하지 않은 모든 것에 대한 체크 박스는 체크되지 않을 것이고, 다른 병렬 td는 체크되지 않을 것입니다 .... 내 문법에 대해 유감스럽게 생각합니다. – user3189194

1

이 같은`여러 HTML 요소에 대한 id`이 좋지 않다 ... 당신은 사용해야 사용하여 HTML을

<table> 
    <thead> 
     <tr> 
      <th><input type="checkbox" name="pay" class="chk-all" data-child='child-1'/>With Pay</th> 
      <th><input type="checkbox" name="pay" class="chk-all" data-child='child-2'/>Without Pay</th> 
     </tr> 
    </thead>  
    <tbody> 
     <tr> 
      <td><input type="checkbox" name="pay" value="With Pay" class="child-1" /></td> 
      <td><input type="checkbox" name="pay" value="Without Pay" class="child-2" /></td> 
     </tr> 
     <tr> 
      <td><input type="checkbox" name="pay" value="With Pay" class="child-1" /></td> 
      <td><input type="checkbox" name="pay" value="Without Pay" class="child-2" /></td> 
     </tr> 
    </tbody> 
</table> 

확인이 Fiddle

관련 문제