jQuery DataTables: Row selection using checkboxes

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.

This is a follow-up article to jQuery DataTables – How to add a checkbox column describing a simple solution to add checkboxes to a table. However proposed solution worked for a table using client-side processing mode only. This article offers universal solution that would work both in client-side and server-side processing modes.

It is loosely based on DataTables example – Row selection but adds extra functionality such as ability to use checkboxes for row selection and other minor improvements.

Example

Example below shows a data table using client-side processing mode where data is received from the server using Ajax. However the same code could be used if data table is switched into server-side processing mode with 'serverSide': true initialization option.

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

Data submitted to the server:


//
// Updates "Select all" control in a data table
//
function updateDataTableSelectAllCtrl(table){
   var $table             = table.table().node();
   var $chkbox_all        = $('tbody input[type="checkbox"]', $table);
   var $chkbox_checked    = $('tbody input[type="checkbox"]:checked', $table);
   var chkbox_select_all  = $('thead input[name="select_all"]', $table).get(0);

   // If none of the checkboxes are checked
   if($chkbox_checked.length === 0){
      chkbox_select_all.checked = false;
      if('indeterminate' in chkbox_select_all){
         chkbox_select_all.indeterminate = false;
      }

   // If all of the checkboxes are checked
   } else if ($chkbox_checked.length === $chkbox_all.length){
      chkbox_select_all.checked = true;
      if('indeterminate' in chkbox_select_all){
         chkbox_select_all.indeterminate = false;
      }

   // If some of the checkboxes are checked
   } else {
      chkbox_select_all.checked = true;
      if('indeterminate' in chkbox_select_all){
         chkbox_select_all.indeterminate = true;
      }
   }
}

$(document).ready(function (){
   // Array holding selected row IDs
   var rows_selected = [];
   var table = $('#example').DataTable({
      'ajax': {
         'url': '/lab/articles/jquery-datatables-checkboxes/ids-arrays.txt' 
      },
      'columnDefs': [{
         'targets': 0,
         'searchable': false,
         'orderable': false,
         'width': '1%',
         'className': 'dt-body-center',
         'render': function (data, type, full, meta){
             return '<input type="checkbox">';
         }
      }],
      'order': [[1, 'asc']],
      'rowCallback': function(row, data, dataIndex){
         // Get row ID
         var rowId = data[0];

         // If row ID is in the list of selected row IDs
         if($.inArray(rowId, rows_selected) !== -1){
            $(row).find('input[type="checkbox"]').prop('checked', true);
            $(row).addClass('selected');
         }
      }
   });

   // Handle click on checkbox
   $('#example tbody').on('click', 'input[type="checkbox"]', function(e){
      var $row = $(this).closest('tr');

      // Get row data
      var data = table.row($row).data();

      // Get row ID
      var rowId = data[0];

      // Determine whether row ID is in the list of selected row IDs 
      var index = $.inArray(rowId, rows_selected);

      // If checkbox is checked and row ID is not in list of selected row IDs
      if(this.checked && index === -1){
         rows_selected.push(rowId);

      // Otherwise, if checkbox is not checked and row ID is in list of selected row IDs
      } else if (!this.checked && index !== -1){
         rows_selected.splice(index, 1);
      }

      if(this.checked){
         $row.addClass('selected');
      } else {
         $row.removeClass('selected');
      }

      // Update state of "Select all" control
      updateDataTableSelectAllCtrl(table);

      // Prevent click event from propagating to parent
      e.stopPropagation();
   });

   // Handle click on table cells with checkboxes
   $('#example').on('click', 'tbody td, thead th:first-child', function(e){
      $(this).parent().find('input[type="checkbox"]').trigger('click');
   });

   // Handle click on "Select all" control
   $('thead input[name="select_all"]', table.table().container()).on('click', function(e){
      if(this.checked){
         $('#example tbody input[type="checkbox"]:not(:checked)').trigger('click');
      } else {
         $('#example tbody input[type="checkbox"]:checked').trigger('click');
      }

      // Prevent click event from propagating to parent
      e.stopPropagation();
   });

   // Handle table draw event
   table.on('draw', function(){
      // Update state of "Select all" control
      updateDataTableSelectAllCtrl(table);
   });

   // Handle form submission event 
   $('#frm-example').on('submit', function(e){
      var form = this;
      
      // 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)
         );
      });
   });

});

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
table.dataTable.select tbody tr,
table.dataTable thead th:first-child {
  cursor: pointer;
}

The following CSS library files are loaded for use in this example to provide the styling of the table:

//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css

Edit on jsFiddle

Other examples

Problem

The problem with handling checkboxes varies based on DataTables initialization settings. 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. In client-side processing mode, the checked state of checkbox is preserved, but only current page is accessible in DOM, all other pages has to be accessible through DataTables API.

Solution

The solution is to create a global variable (rows_selected in our example) to store a list of selected row IDs and use it to display checkbox state and highlight selected rows.

Highlights

Javascript

  • Storing selected row IDs

       // Array holding selected row IDs
       var rows_selected = [];

    Define array holding selected row IDs.

  • Columns definition

          'columnDefs': [{
             'targets': 0,
             'searchable': false,
             'orderable': false,
             'width': '1%',
             'className': 'dt-body-center',
             'render': function (data, type, full, meta){
                 return '<input type="checkbox">';
             }
          }],
    

    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.

  • Initial sorting order

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

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

  • Row draw callback

          'rowCallback': function(row, data, dataIndex){
             // Get row ID
             var rowId = data[0];
    
             // If row ID is in the list of selected row IDs
             if($.inArray(rowId, rows_selected) !== -1){
                $(row).find('input[type="checkbox"]').prop('checked', true);
                $(row).addClass('selected');
             }
    

    Callback function rowCallback will be called before each row draw and is useful to indicate the state of the checkbox and row selection. We use internal DataTables CSS class selected.

    Important

    Please note that in the example above row ID is stored as first element of the row data array and is being retrieved by using the following code.

             // Get row ID
             var rowId = data[0];

    If you’re using data structure other than described in the article, adjust this and other similar lines accordingly.

  • Form submission

       // Handle form submission event 
       $('#frm-example').on('submit', function(e){
          var form = this;
          
          // 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)
             );
          });
       });
    

    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 selected checkboxes from all pages we need to iterate over rows_selected array and add a hidden <input> element to the form with some name (id[] in our example) and row ID as a value. This will allow all the data to be submitted.

    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.

HTML

<table id="example" class="display select" cellspacing="0" width="100%">

Additional CSS class select is used to change cursor when hovering over table rows for specific tables only.

CSS

table.dataTable.select tbody tr,
table.dataTable thead th:first-child {
  cursor: pointer;
}

Display cursor in the form of a hand for table rows and first cell in the table heading where “Select all” control is located.

You May Also Like

Comments

  1. I’m having a problem.
    I implemented this and “var rowId = data[0]; ” coming “Undefined”. May I know the possible reasons why I get this?

  2. Sir i’m having a problem with adding a input type within the datatable. for example if I added input type on data[4], it outputs the whole . Is it possible to just output the value of the input type instead of the whole input type?

        1. Use $('input[type="number"]', $row).val() instead of data[4]. There are other issues with your code, for example checkbox is toggled when arrows in quantity field are clicked (corrected in my example) or multiple use of ID bw_qty (IDs should be unique). See updated example.

  3. 'rowCallback': function(row, data, dataIndex){
       // Get row ID
       var rowId = data[0];
    
       // If row ID is in the list of selected row IDs
       if($.inArray(rowId, rows_selected) !== -1){
          $(row).find('input[type="checkbox"]').prop('checked', true);
          $(row).addClass('selected');
       }
    

    After use this method unable to use API cells().checkboxes.select(state) Checks a checkbox in multiple cells.
    Use API for count selected checbox. Its not working checked box show its checked but when i click its work otherwise not.

  4. Hello sir, thank you for great example. Do you have an example on how to send the data that are checked to another list once we hit submit.
    Thank you.

  5. I cannot get this to work on a 2-page listing. I have a table containing 22 rows of data. The first page shows the first 10 rows. When I click on the “Select All” checkbox only the checkboxes on the first page are set to “selected” (checked). When I click to view the second page of the list, the checkboxes in the final two rows on that second page are not checked.

    1. Gary, in this post above I attempted to make behavior of the table in both client-side and server-side processing modes to behave the same, i.e. clicking on “Select All” control only selects checkboxes on the current page only. I now see that it’s not mentioned anywhere in the article which is why it is confusing. I will probably need to update the code and the article.

      Later in 2016 I wrote I plug-in jQuery DataTables Checkboxes that simplifies handling of checkboxes with jQuery DataTables where it has become configurable option to use “Select All” to select checkboxes on current or all pages. See if you can use jQuery DataTables Checkboxes for your project instead.

      1. Hell Michael. Thanks for the reply.
        OK, so I implemented your Checkboxes solution on your “JQuery DataTables Checkboxes” page as you suggested and it is working great!.

        However, while this is working as desired, I still need to be able to invoke program code not only when the “Select ALL” checkbox is clicked, but also when each individual row checkbox is clicked. For this should I referr to your solution mentioned here on this “Row selection using checkboxes” pages or can you please point me to the correct pages on your site that I can refer to for these implementations.

        Thanks again for your assistance. Gary

  6. Hi, not sure if this is related to you post. I have a button and a span on the datatables toolbar. i have to click events
    that work off button and span. but when i click the select all check box the click events for button and span do not work.
    is there something in the toolbar that is changing button and span? button say [type=button]:not(:disabled).

  7. Hi, thanks for the code but it doesn’t work after I click on select_all checkbox. It didn’t check checkboxes inside body.

    But after I remove the line:

    var $table = table.table().node();
    

    it works but I cant uncheck child checkboxes with error $table is not defined.

    After I add back this line no error but code doesn’t work. Can you help?

  8. Hi Michael!
    I would to get data value of the selected element.

    I do this:
    $.each(rows_selected, function (index, rowId) {
    var data = table.row(index).data();
    fed_id = data[‘federation_id’];
    console.log(fed_id);
    });

    But fed_id has wrong value, has the value of the first row in the table instead the selected one.

    Thanks
    Luca

  9. Hi,

    We had integrated datatables.net plugin with below 2 extensions:

    https://github.com/gyrocode/jquery-datatables-checkboxes

    https://datatables.net/extensions/select/

    Your help was awesome during integration of above extensions in our project which was using jQuery and bootstrap.

    Now, we are planning to upgrade our project to use Angular framework.

    I am really confused now if datatables.net plugin and above 2 extensions will work in upgraded Angular project?

    Are above plugin and extensions supported in Angular or if I need other plugins/extensions for Angular support?

    Thank you.

  10. If I use div instead of table like

    <div class=”divTable greyGridTable” id=”display select”>

          <div class=”divTableHeading”>

           <div class=”divTableRow”>

            <div class=”divTableHead”>Date</div>

            <div class=”divTableHead”> Name</div>

            <div class=”divTableHead”>Day</div>

          <div> <input name=”select_all” value=”1″ type=”checkbox”> </div>

           </div>

          </div>

          <div class=”divTableBody” id=”List”></div>

         </div>

    Than what should be css code

  11. Hi, Michael.

    How to submit the selected names in the checkboxes to another table in the database?

    Do you have a working example with codes?

  12. Hi Michael, hope your safe and well.

    I’m looking for a solution thatwill enable a user to select multiple rows in the datatable and on clicking submit i want to update another MYSQL table based on 2 fields in the rows the user selected in the datatable.

    I’m really new to datatables and wondered if your solution here would work for me.
    I can see the output in your example (i selected the first 2 rows and the following was shown)

    example_length=10&select_all=1&id%5B%5D=5&id%5B%5D=25

    But i really don’t understand what this output is and how I can use it.

    Any help and direction would be appreciated.

    Regards

    Alan

  13. I tried this code with server-side processing but the search functionality is not working now.
    Can you provide the server-side processing code to fetch the data 

Leave a Reply

(optional)

This site uses Akismet to reduce spam. Learn how your comment data is processed.