2011-09-23 4 views
1

에있는 모든 체크 박스를 확인 나는이 같은 테이블 설정이 있습니다jQuery를

<table> 
    <thead> 
     <th> 
      <input type="checkbox" class="check-all" /> 
     </th> 
     <th> 
      Title 
     </th> 
    </thead> 
    <tbody> 
     <tr> 
      <td><input type="checkbox" /></td> 
      <td>Name</td> 
     </tr> 
     <tr> 
      <td><input type="checkbox" /></td> 
      <td>Name 2</td> 
     </tr> 
    </tbody> 
</table> 

내가 '체크인을 모두'클래스 헤더의 체크 박스가 선택되어 있으므로 때 가지고 노력하고, 모든 확인 아래 체크 박스.

이 내가 무슨이지만

 $('.check-all').click(
     function(){ 
      $(this).parent().parent().parent().find("input[type='checkbox']").attr('checked', $(this).is(':checked')); 
     } 
    ) 

어떤 아이디어를 작동하지 않는 것? 고맙습니다!

답변

3

가장 가까운 테이블 태그를 찾으려면 먼저 jQuery.closest()을 사용해야합니다.

$('.check-all').click(function() { 
    $(this).closest('table').find("input:checkbox").attr('checked', this.checked); 
}); 

초. 당신이 jQuery를 1.6 이상을 사용하는 경우가에서 부울 값을, 마지막으로 jQuery.prop()

$('.check-all').click(function() { 
    $(this).closest('table').find("input:checkbox").prop('checked', this.checked); 
}); 

를 사용해야 체크 모든 당신이 단순히 HTML DOM this.checked

0

I을 사용할 수 있습니다 jQuery 오브젝트를 필요로하지 않는 상자 부모님을 잃어버린 길. 이 시도 :) :

$(this).closest("table").find("input[type='checkbox']").attr('checked', $(this).is(':checked')); 

편집 :

P.S.을 @ John Hartsock이 구문을 약간 변경했습니다. 나는 구문을 그대로 놔뒀지 만 그의 구문은 더 낫다. (또는 단지 .find (": checkbox")를 사용할 수있다.) 나는 jquery가 모든 입력을 얻는 것보다 훨씬 효율적인 방법으로 체크 박스를 찾을 수 있다고 생각한다. 다음은 체크 박스가 있는지 확인하기 위해 속성 "유형"을 검사합니다. 잠시 다시

0

I wrote an article about this. 모든 관련 확인란을 같은 클래스를주는 경우가 더 쉬울 것이다.

UPDATE

Here's a jsFiddle 여기서 코드를 복사하면 시간이 더 많이 걸릴 것입니다.

HTML

<table> 
    <thead> 
     <tr> 
      <th> 
       <input type="checkbox" class="check-all" /> 
      </th> 
      <th>Check All Below</th> 
     </tr> 
     <tr><th><hr /></th></tr> 
    </thead> 
    <tbody> 
     <tr> 
      <td><input type="checkbox" class="groupOne" /></td> 
      <td>Name</td> 
     </tr> 
     <tr> 
      <td><input type="checkbox" class="groupOne" /></td> 
      <td>Name 2</td> 
     </tr> 
    </tbody> 
</table>

자바 스크립트

var $_checkAll = $('.check-all'); 
var $_groupOne = $('.groupOne'); 

$_checkAll.click(function(){ 
    $_groupOne.prop('checked', $_checkAll.prop('checked')); 
}); 

/* If I uncheck a groupOne checkbox, uncheck the related "check all" */ 
$_groupOne.click(function(){ 
    if (!$(this).prop('checked')) { 
     $_checkAll.prop('checked', false); 
    } 
}); 

/* Checking the "check all" checkbox when all groupOne checkboxes 
have been checked is left as homework. */