2014-05-13 54 views
9

我知道這看起來原始的「檢查所有」,但我一直在努力執行了整整一天,也許是因爲我不能完全理解如何使用API​​,我使用數據表1.10.0,我有分頁功能表中,每一行中有一個複選框,我需要有一個「檢查所有按鈕」,將您在網頁中的所有複選框,問題是它只檢查的複選框在當前頁面中,並且其他頁面未被選中,這應該很容易,但我無法弄清楚!答案我發現使用「fnGetNodes」,這似乎是過時和不使用的版本1.10數據表1.10通過jQuery

編輯:這是我的標記

 <table class="table table-striped table-bordered table-hover" id="numbers_table"> 
       <thead> 
        <tr> 
         <th><input type="checkbox" id="checkall" title="Select all" onClick="toggle(this)"/></th> 
         <th>Number</th> 
         <th>Company</th> 
         <th>Tags</th> 
        </tr> 
       </thead> 
       <tbody> 
        <% _.each(array, function (value) { %> 
        <tr> 
         <td><input type='checkbox' name='numbers[]' value='<%=value.id%>'/></td> 
         <td><%= value.number %></td> 
         <td><%= value.company %></td> 
         <td><%= value.tags %></td> 
        </tr> 
        <% }) %> 
       </tbody> 
      </table> 

    <button type="button" class="btn btn-primary" id="checkall2">SELECT ALL</button> 

<script> 

$(document).ready(function() { 

    $('#numbers_table').dataTable({ 
     //"bPaginate": false, 
     "aoColumnDefs": [ 
     { "bSortable": false, "aTargets": [ 0 ] } 
    ] 
     }); 

    $("#checkall2").click(function() { // a button with checkall2 as its id 
     $(':checkbox').prop('checked', true); // all checkboxes, you can narrow with a better selector 
    }); 
}); 
</script> 
+1

請提供更多的細節,比如實際的代碼你使用。 –

+0

@LaughDonor我添加的代碼^ – mbahaa

回答

3

試試這個代碼:

var table = $('#numbers_table').DataTable(); 

var cells = table 
    .cells(":checkbox") 
    .nodes(); 

$(cells).prop('checked', true); 

Source.

+2

這是行不通的,但下面的答案definitly – Gayan

+0

同意了,不知道爲什麼選擇這個答案的功能。也許在以前的版本中是正確的,我沒有時間檢查。就目前而言,這不是解決方案。 –

1

這真的不是那麼難,但是沒有看到你的我的標記只能提供一個通用的例子 -

$('input[value="Check All"]').click(function() { // a button with Check All as its value 
    $(':checkbox').prop('checked', true); // all checkboxes, you can narrow with a better selector 
}); 
+1

我已經實施了類似的代碼,該問題是由數據表分頁造成的,選擇適用於表中查看當前頁面的元素,在其他頁面複選框處於未選中狀態 – mbahaa

+0

您必須添加邏輯到您的分頁邏輯,因爲直到您點擊分頁鏈接纔會加載數據。 –

+0

了「分頁邏輯」不是我的,數據表是一個插件,他們有成熟的API,我已經找到答案了這個問題,但顯然它使用舊版本的API函數,如「fnGetNodes」,我不能似乎找到這些問題的答案目前使用的API – mbahaa

10

這應該爲你工作

var table = $('#numbers_table').DataTable(); 

    $('#checkall').click(function() { 
     $(':checkbox', table.rows().nodes()).prop('checked', this.checked); 
    }); 
+0

如何在我選擇的行上應用css? –

+0

如何可能的是'table.rows()'引發此異常: '未捕獲的類型錯誤:table.rows不在函數 :2:7 在Object.InjectedScript._evaluateOn(:895: 140) at Object.InjectedScript._evaluateAndWrap(:828:34) at Object.InjectedScript.evaluate(:694:21)' – nicolimo86

2

如果還是不行嘗試使用API​​()關鍵字:

$('#YourCheckBoxId').on('click', function() { 
    var rows = YourDatatableVariable.api().rows({ 'search': 'applied' }).nodes(); 
    $('input[type="checkbox"]', rows).prop('checked', this.checked); 
});