2011-04-01 47 views
1

我試圖做一次檢查,一旦點擊將檢查該表的特定列中的所有框。所以說,如果它是在第3列:點擊它將檢查列3中所有行的所有複選框。但我也希望它檢測它在哪一​​列。自動檢測並檢查所有表格列

這是我有到目前爲止,我已經得到它做的一個或另一個,但不是在同一時間:

  $('.checkall').click(
       function(){ 
        var col = $(this).parent().children().index($(this)); 
        $(this).parent().parent().parent().parent().find("td:eq("+col+") input[type='checkbox']").attr('checked', $(this).is(':checked')); 
       } 
      ); 
+1

[這個鏈接](http://beckelman.net/Demos/jQuerySelectAllCheckBoxesPlugin/Default.aspx)對你有用嗎? – Town 2011-04-01 22:25:14

+0

@Town你應該把它作爲一個答案,因爲它接縫很好的答案 – 2011-04-01 22:30:27

+0

nope不要讓我插入var col ...至少我不能讓它工作 – Ruttyj 2011-04-01 22:32:44

回答

1

這應該工作:

$(".checkall").click(function(){ 
    var $table = $(this).closest("table"); 
    var col = $(this).closest("tr").children().index($(this).closest("td")); 
    var index = col + 1; // offset for nth-child 
    $table.find("td:nth-child("+index+") input:checkbox").attr("checked",$(this).is(":checked")); 
}); 

jsfiddle.net

+0

完美的作品 – Ruttyj 2011-04-02 03:02:44

0

這將做的工作。 評論,如果這不是正是你想要

HTML內容:

<table border="1"> 
    <tr> 
     <td>All<input type="checkbox" value="" class="checkAll"></td> 
     <td><input type="checkbox" value=""></td> 
     <td><input type="checkbox" value=""></td> 
     <td><input type="checkbox" value=""></td> 
    </tr> 
    <tr> 
     <td>All<input type="checkbox" value="" class="checkAll"></td> 
     <td><input type="checkbox" value=""></td> 
     <td><input type="checkbox" value=""></td> 
     <td><input type="checkbox" value=""></td> 
    </tr> 
</table> 

的javascript:

<script type="text/javascript"> 
    $('tr').find('input:checkbox').not('.checkAll').change(function() 
    { 
     var checkboxes = $(this).parent().parent().find(':checkbox').not('.checkAll'); 
     var checkAll = $(this).parent().parent().find('.checkAll'); 
     if (!checkboxes.not(":checked").not(".checkAll").length) 
      checkAll.attr("checked", true); 
     if (!checkboxes.filter(":checked").not(".checkAll").length) 
      checkAll.attr("checked", false); 

    }); 
    $(".checkAll").change(function() 
    { 
     $(this).parent().parent().find(':checkbox').attr('checked', this.checked); 
    }); 
</script>