close

先講重點:

取得每一列資料要使用dataTable的function,才能取到跨分頁的所有資料,不能單純使用jQuery去取得(使用jQuery取得只能抓到該分頁的列資料)

var rows = oTable.rows().nodes();    // 使用dataTable內建function取得所有列

$('input[type="checkbox"]', rows).prop('checked', true);    // 再把rows丟入jQuery selector中做全選功能

 

p.s. dataTable後來有內建checkbox選擇功能,但還來不及研究,就先這樣。

--

jQuery DataTables: How to add a checkbox column

Update
 January 15, 2016
See jQuery DataTables Checkboxes plug-in that makes it much easier to add checkboxes and multiple row selection to a table powered by jQuery DataTables. It works in client-side and server-side processing modes, supports alternative styling and other extensions.

Example

Client-side processing mode with Ajax sourced data

Example below shows a table in client-side processing mode where data is received from the server via Ajax request.

NamePositionOfficeExtn.Start dateSalary
NamePositionOfficeExtn.Start dateSalary
Tiger Nixon System Architect Edinburgh 5421 2011/04/25 $320,800
Timothy Mooney Office Manager London 7580 2008/12/11 $136,200
Unity Butler Marketing Designer San Francisco 5384 2009/12/09 $85,675
Vivian Harrell Financial Controller San Francisco 9422 2009/02/14 $452,500
Yuri Berry Chief Marketing Officer (CMO) New York 6154 2009/06/25 $675,000
Zenaida Frank Software Engineer New York 7439 2010/01/04 $125,250
Zorita Serrano Software Engineer San Francisco 4389 2012/06/01 $115,000
Showing 51 to 57 of 57 entries
Previous123456Next

Data submitted to the server:

example_length=10&select_all=1&id%5B%5D=5&id%5B%5D=25&id%5B%5D=3&id%5B%5D=19&id%5B%5D=28&id%5B%5D=6&id%5B%5D=43&id%5B%5D=23&id%5B%5D=51&id%5B%5D=4&id%5B%5D=13&id%5B%5D=9&id%5B%5D=20&id%5B%5D=57&id%5B%5D=24&id%5B%5D=46&id%5B%5D=29&id%5B%5D=2&id%5B%5D=34&id%5B%5D=26&id%5B%5D=18&id%5B%5D=14&id%5B%5D=52&id%5B%5D=7&id%5B%5D=38&id%5B%5D=37&id%5B%5D=41&id%5B%5D=11&id%5B%5D=21&id%5B%5D=50&id%5B%5D=27&id%5B%5D=54&id%5B%5D=53&id%5B%5D=35&id%5B%5D=56&id%5B%5D=16&id%5B%5D=31&id%5B%5D=42&id%5B%5D=17&id%5B%5D=33&id%5B%5D=12&id%5B%5D=8&id%5B%5D=44&id%5B%5D=47&id%5B%5D=55&id%5B%5D=30&id%5B%5D=10&id%5B%5D=32&id%5B%5D=15&id%5B%5D=45&id%5B%5D=1&id%5B%5D=40&id%5B%5D=36&id%5B%5D=39&id%5B%5D=22&id%5B%5D=48&id%5B%5D=49

 

$(document).ready(function (){
   var table = $('#example').DataTable({
      'ajax': {
         'url': '/lab/articles/jquery-datatables-how-to-add-a-checkbox-column/ids-arrays.txt'
      },
      'columnDefs': [{
         'targets': 0,
         'searchable': false,
         'orderable': false,
         'className': 'dt-body-center',
         'render': function (data, type, full, meta){
             return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
         }
      }],
      'order': [[1, 'asc']]
   });

   // Handle click on "Select all" control
   $('#example-select-all').on('click', function(){
      // Get all rows with search applied
      var rows = table.rows({ 'search': 'applied' }).nodes();
      // Check/uncheck checkboxes for all rows in the table
      $('input[type="checkbox"]', rows).prop('checked', this.checked);
   });

   // Handle click on checkbox to set state of "Select all" control
   $('#example tbody').on('change', 'input[type="checkbox"]', function(){
      // If checkbox is not checked
      if(!this.checked){
         var el = $('#example-select-all').get(0);
         // If "Select all" control is checked and has 'indeterminate' property
         if(el && el.checked && ('indeterminate' in el)){
            // Set visual state of "Select all" control
            // as 'indeterminate'
            el.indeterminate = true;
         }
      }
   });

   // Handle form submission event
   $('#frm-example').on('submit', function(e){
      var form = this;

      // Iterate over all checkboxes in the table
      table.$('input[type="checkbox"]').each(function(){
         // If checkbox doesn't exist in DOM
         if(!$.contains(document, this)){
            // If checkbox is checked
            if(this.checked){
               // Create a hidden element
               $(form).append(
                  $('<input>')
                     .attr('type', 'hidden')
                     .attr('name', this.name)
                     .val(this.value)
               );
            }
         }
      });
   });

});

In addition to the above code, the following Javascript library files are loaded for use in this example:

//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js
//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js

 Edit on jsFiddle

Highlights

Javascript

  • Columns definition

    'columnDefs': [{
       'targets': 0,
       'searchable':false,
       'orderable':false,
       'className': 'dt-body-center',
       'render': function (data, type, full, meta){
           return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
       }
    }],

    Option columnsDef is used to define appearance and behavior of the first column ('targets': 0).

    Searching and ordering of the column is not needed so this functionality is disabled with searchable and orderable options.

    To center checkbox in the cell, internal DataTables CSS class dt-body-center is used.

    Option render is used to prepare the checkbox control for being displayed in each cell of the first column. We use a trick with $('<div/>').text(data).html() to encode HTML entities that could be present in the data.

    Another trick here is to give input element a name with square brackets (id[]). This will make handling of list of checked checkboxes easier on the server-side. For example, PHP will convert all these parameters to an array, see PHP FAQ: How do I get all the results from a select multiple HTML tag for more information.

  • Initial sorting order

    'order': [[1, 'asc']],

    By default, DataTables sorts the table by first column in ascending order. By using order option we select another column to perform initial sort.

  • “Select all” control

    // Handle click on "Select all" control
    $('#example-select-all').on('click', function(){
       // Get all rows with search applied
       var rows = table.rows({ 'search': 'applied' }).nodes();
       // Check/uncheck checkboxes for all rows in the table
       $('input[type="checkbox"]', rows).prop('checked', this.checked);
    });

    We attach event handler to handle clicks on “Select all” control. To retrieve all checkboxes that are present in the table taking into account currently applied filter, we use rows() method using appropriate selector-modifier.

    // Handle click on checkbox to set state of "Select all" control
    $('#example tbody').on('change', 'input[type="checkbox"]', function(){
       // If checkbox is not checked
       if(!this.checked){
          var el = $('#example-select-all').get(0);
          // If "Select all" control is checked and has 'indeterminate' property
          if(el && el.checked && ('indeterminate' in el)){
             // Set visual state of "Select all" control
             // as 'indeterminate'
             el.indeterminate = true;
          }
       }
    });

    The purpose of the event handler above is to detect when one of the checkboxes in the table is unchecked when “Select all” control was checked. When that happens, we can set “Select all” control to a special state indeterminate to indicate that only some checkboxes are checked.

  • Form submission

    // Handle form submission event
    $('#frm-example').on('submit', function(e){
       var form = this;
    
       // Iterate over all checkboxes in the table
       table.$('input[type="checkbox"]').each(function(){
          // If checkbox doesn't exist in DOM
          if(!$.contains(document, this)){
             // If checkbox is checked
             if(this.checked){
                // Create a hidden element
                $(form).append(
                   $('<input>')
                      .attr('type', 'hidden')
                      .attr('name', this.name)
                      .val(this.value)
                );
             }
          }
       });
    });

    When table is enhanced by jQuery DataTables plug-in, only visible elements exist in DOM. That is why by default form submits checkboxes from current page only.

    To submit checkboxes from all pages we need to retrieve them with $() API method. Then for each checkbox not present in DOM we add a hidden element to the form with the same name and value. This allows all the data to be submitted.

    It’s even more simple if form submission is performed via Ajax. In that case URL-encoded data for submission can be produced using the code below:

    var data = table.$('input[type="checkbox"]').serialize();

    For more information on submitting the form elements in a table powered by jQuery DataTables, please see jQuery DataTables: How to submit all pages form data.

Server-side processing

Please note that the example and code above will work for client-side processing mode only.

In server-side processing mode ('serverSide':true) elements <input type="checkbox"> would exist for current page only. Once page is changed, the checked state of the checkboxes would not be preserved.

See jQuery DataTables Checkboxes for a universal solution that will work for server-side processing mode as well.

--

轉自 https://www.gyrocode.com/articles/jquery-datatables-how-to-add-a-checkbox-column/

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 dizzy03 的頭像
    dizzy03

    碎碎念

    dizzy03 發表在 痞客邦 留言(0) 人氣()