jQuery DataTables Checkboxes

Checkboxes is an extension for the jQuery DataTables library that provides universal solution for working with checkboxes in a table.

Example

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

Name Position Office Extn. Start date Salary
Name Position Office Extn. Start date Salary

Selected rows data:


Form data as submitted to the server:


$(document).ready(function (){
   var table = $('#example').DataTable({
      'ajax': '/lab/jquery-datatables-checkboxes/ids-arrays.txt',
      'columnDefs': [
         {
            'targets': 0,
            'checkboxes': {
               'selectRow': true
            }
         }
      ],
      'select': {
         'style': 'multi'
      },
      'order': [[1, 'asc']]
   });


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

      // Iterate over all selected checkboxes
      $.each(rows_selected, function(index, rowId){
         // Create a hidden element 
         $(form).append(
             $('<input>')
                .attr('type', 'hidden')
                .attr('name', 'id[]')
                .val(rowId)
         );
      });
   });
});

Edit on jsFiddle

Installation

Include two extra files in addition to jQuery and jQuery DataTables plugins.

<link type="text/css" href="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.6/css/dataTables.checkboxes.css" rel="stylesheet" />
<script type="text/javascript" src="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.6/js/dataTables.checkboxes.min.js"></script>

Usage

In your jQuery DataTables initialization code add checkboxes option for the column where you want the checkboxes to appear using either columns or columnDefs options.

If you’re using Select extension, you may want to enable multiple row selection using select.style option.

If checkboxes are located in the first column, you may also want to sort by column other than first which is performed by default with order option.

For example:

var table = $('#example').DataTable({
   'columnDefs': [
      {
         'targets': 0,
         'checkboxes': {
            'selectRow': true
         }
      }
   ],
   'select': {
      'style': 'multi'
   },
   'order': [[1, 'asc']]
});

Known Limitations

  • Column containing checkboxes must have unique data. Using columns.data option set to null for the column containing checkboxes will result in unexpected behavior.
  • Selecting rows on all pages using columns.checkboxes.selectAllPages option in server-side processing mode is currently not possible. In this mode rows on current page only are selected when “select all” control is clicked.

Copyright

Gyrocode,

License

MIT License, opensource.org/licenses/MIT