jQuery DataTables: Row selection using checkboxes and Select extension

We are pleased to introduce jQuery DataTables Checkboxes extension that makes it easy to add a checkbox columns to 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:


Please visit dedicated jQuery DataTables Checkboxes page to download the code, view examples and documentation.

You May Also Like

Comments

  1. I have used custom date range filter in datatable. So I have initialize datatable instance in function. Now when I click trigger a function to get the values of checkbox it show me an error that instance variable is not defined.

    
    $(document).ready(function() {
    fetch_data();
    
        function fetch_data(is_date_search = '', date = '', type = '') {
            var table = $('#customerList').DataTable({
                "processing": true,
                "serverSide": true,
                "select": {
                     'style': 'multi'
                },
                "order": [],
                "ajax": {
                    "url": "",
                    "type": "POST",
                    "data": {
                        is_date_search: is_date_search,
                        date: date,
                        type: type
                    }
                },
                 "columnDefs": [{
                    "targets": 0,
                    'searchable': false,
                    'orderable': false,
                    'checkboxes': {
                       'selectRow': true
                    }
                    // 'className': 'dt-body-center',
                    // 'render': function (data, type, full, meta){
                    //      return '<input type="checkbox" name="id[]" class="theClass" value="' + $('').text(data).html() + '">';
                    //  }
                },
                {
                    "name": "sr_no",
                    "targets": 1
                },
                {
                    "name": "c.name",
                    "targets": 2
                },
                {
                    "name": "c.mobile",
                    "targets": 3
                },
                {
                    "name": "c.email",
                    "targets": 4
                },
                {
                    "name": "c.birthdate",
                    "targets": 5
                },
                {
                    "name": "c.anniversary_date",
                    "targets": 6
                },
                {
                    "name": "c.created_at",
                    "targets": 7
                },
                {
                    "name": "feedback_count",
                    "targets": 8
                },
                {
                    "name": "rewards_points",
                    "targets": 9
                },
                {
                    "name": "coupons",
                    "targets": 10
                },
    
            ]
            });
    
            //draw table
            table.columns().every(function() {
                var table = this;
                $('input', this.header()).on('keyup change', function() {
                console.log(table.search());
                    if (table.search() !== this.value) {
                        table.search('')
                        table.columns().search('')
                        table.search(this.value).draw();  
                    }
                });
            });
        }
    
    
        //tooltip
    
    
    
    
        var start = moment().subtract(29, 'days');
        var end = moment();
    
        function cb(start, end) {
            $('#birthdate_picker').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
            $('#anniversary_date').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
            $('#created_at').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
        }
    
        $('#birthdate_picker').daterangepicker({
            startDate: start,
            endDate: end,
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')]
            }
        }, cb);
    
    
        cb(start, end);
    
    
    
    
        $(document).on('click','#message_to_send', function() {
            // var selectedIds = table.columns().checkboxes.selected()[0];
    
            // if (selectedIds != '') {
            //     $('#messageForm')[0].reset();
            //     $('#message_model').modal('show');
            // } else {
            //     alert('Please Select At least one contact number');
            // }
           var checkbox_value = [];
            var rows_selected = table.column(0).checkboxes.selected();
            // var rowcollection =  oTable.$(".dt-checkboxes:checked", {"page": "all"});
            rows_selected.each(function(index,elem){
                checkbox_value.push($(elem).val());
            });
            console.log(checkbox_value);
    
        });
    
    
    
    
    
        $('#birthdate_picker').on('change', function() {
            var birthdate = $('#birthdate_picker').val();
    
            if (birthdate) {
                $('#customerList').DataTable().destroy();
                fetch_data('yes', birthdate, 'c.birthdate');
            } else {
                alert('Date is required');
            }
    
        });
    
    
    });
    
    });
    
  2. var rows_selected = table.column(0).checkboxes.selected();
    

    With this the id will be fetching perfectly.
    But, By checking the multiple check box or single check box i need the column, such as “name” or “position” with separated by comma,with respect to the checkbox checked on the particular rows.

    I tried with,

    var rows_selected = table.column(1).checkboxes.selected();
    

    or

    var rows_selected= table.columns().checkboxes.selected()[0][1];
    

    Nothing will happen, please help me.

    1. Please assign the variable globally

      example:

      var tbl;
      
      tbl = $('#Reportpolicy').DataTable(
      
      then 
        function getSelected()
          {
              var selectedIds = tbl.columns().checkboxes.selected()[0];
              console.log(selectedIds)
      
              selectedIds.forEach(function (selectedId) {
                  alert(selectedId);
              });
          }
      

      if you have any doubts, whatsapp me (+601133269433)

      1. Hi Prabu I tried your code but I’m not able to get value or a column different from the id one.
        For example I would to get value of the column with index 10 of the row checked. How can I do this? And if the column could be hidden?

        Thanks

  3. Hello Michael,
    My name is Jonatan I’m from Brazil, first thanks for the library.
    I am trying to deselect all checkboxes using server side, is there any way to do this?

  4. Hi,

    I have implemented below example:

    https://www.gyrocode.com/projects/jquery-datatables-checkboxes/examples/styling/icheck/

    But it has 2 issues which we need to fix:

    1. Checking any row level checkbox also checks the header checkbox. Can this be avoided?

    2. Also, if I check the header checkbox it will check all the row level checkboxes. Then if I uncheck any of row level checkbox, header checkbox is still checked and it should be unchecked. Can this be fixed?

    Both these issues are present in your above icheck example link.

    Thanks for great plugin.

  5. I tested this code with Data table DataTables 1.10.16 and it gives me an error “Uncaught TypeError: Cannot read property ‘info’ of undefined”, is there any suggestions to solve that?

  6. Hello Michael

    Thanks for that great plugin!
    I have two questions, one of that is that I suffer from the same problem as Jacob a few posts above me – if I click a random checkbox I get the header one selected.
    The second one is, that I cannot use the “stateSave”: true option correctly (this is why I actually came here from datatables.net) – I do not use a reload button, but have it all in a setInterval() to update the data dynamically as proposed on datatables.net.

    included:

    
    https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js
    //cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js
    //cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css
    //gyrocode.github.io/jquery-datatables-checkboxes/1.2.11/css/dataTables.checkboxes.css//gyrocode.github.io/jquery-datatables-checkboxes/1.2.11/js/dataTables.checkboxes.min.js">
    
  7. Hi Michael

    Thanks for your plugin. I’m trying using it, but I have problems. I don’t want use it for select/unselect rows. My intentions is use it as a field from a datatable in DB (in ordern have or not permissions for doing a action in a role). Therefore, I need ckecked/unchecked the check depending of if source is true or false (in this case my source is a html table).

    I thought use your example “Select checkboxes on page load” and modify it. But it’s not working. I cannot check programatically my checkbox. What am I doing wrong?

            $(document).ready(function () {
                let table = $('#tbPermisos').DataTable({
                    columnDefs: [
                        {
                            targets: [0, 3, 4, 5],
                            visible: false
                        },
                        {
                            targets: 1,
                            orderable: false
                        },
                        {
                            targets: 2,
                            searchable: false, checkboxes: {
                                    selectRow: false,
                                    selectAll: false
                                
                            },
                            createdCell: function (td, cellData, rowData, row, col) {
    							this.api().cell(td).checkboxes.select();
    							
                                //this.api().cell(td).checkboxes.prop('checked', true);
                            },
                        }
                    ],               
                });
    
  8. Hi,

    I use the your nice checkbox plugin with jquery datatables plugin. I also use excel button with datatables. 

    I want to export to excel file only checked rows. 

    How can I achieve this?

    Thanks in advance

    1. Sorry for the late reply. The answer depends on the processing mode you are using.

      If you’re using client-side processing mode, built-in excel button has exportOptionsexportOptions option. You can use this option to instruct DataTables to export selected rows only. For example:

      
      $('#myTable').DataTable( {
          // ... skipped ...
          buttons: [
              {
                  extend: 'excel',
                  exportOptions: {
                      modifier: {
                          selected: true
                      }
                  }
              }
          ]
      } );
      

      With server-side processing mode it will be more complex.

      1. Thanks for replying.

        I use serverSide processing. Because our dataset has too much data. 

        For this complexity, do you have any sample code for an entry point?

          1. Actually, I used your above option as in DataTables feature. But it doesn’t work.

             I use it for log , history, product and etc type of data. 

            I have generic function that used by many screens.And I can share it below. 

            var grid = {
                order: [],
                allcount: 0,
                generate: (gridName, columnDefs, exportColumns, url, method, token, isCheck = false, callback) => {
                    // debugger;
            
                    $.fn.dataTable.ext.errMode = 'throw';
            
                    let table = $('#' + gridName).DataTable({
                        responsive: true,
                        //info: false,  //display info part at the bottom=left
                        autoWidth: false,
                        cache: false,
                        scrollCollapse: true,
                        paging: true,
                        pagingType: 'simple_numbers',
                        lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, 'All']],          
                        buttons: [
                            {
                                extend: 'collection',
                                text: 'Export',
                                buttons: [
                                    {
                                        extend: 'excel',
                                        // text: '<u>E</u>xcel',
                                        //text: '<span data-i18n="Rez.lbl-table-excel-button">Export</span>',
                                        exportOptions: {
                                            columns: exportColumns,                               
                                        },
                                        // key: {
                                        //     key: 'e',
                                        //     altKey: true
                                        // }
                                    },
                                ]
                            },
                        ],
                        "processing": "true",
                        "serverSide": "true",
                        "ajax": {
                            "url": url,
                            "data": function (d) {
                                let order = grid.order;
                                let columnIndex = d.order[0].column;
            
                                return {
                                    //searchStrings: [d.search.value],
                                    searchStrings: d.search.value !== "" ? d.search.value : [],
                                    index: Math.floor(d.start / d.length), //d.draw - 1, 
                                    size: (d.length !== -1 ? d.length : parseInt(grid.allcount)),
                                    orderBy: order[columnIndex] + (d.order[0].dir === "asc" ? "" : ":D")
                                }
                            },
                            "beforeSend": xhr => {   //Include the bearer token in header                    
                                //console.log(localStorage.token);
                                xhr.setRequestHeader("Authorization", 'Bearer ' + token);
                            },
                            contentType: "application/json",
                            dataType: "json",
                            dataSrc: function (data) {
                                //debugger;
            
                                //in order to get all records when select 'All' in length menu of datatables
                                grid.allcount = data.Data.Count;
            
                                data.recordsFiltered = data.Data.Count;
                                data.recordsTotal = data.Data.Count;
                                data.data = data.Data.Items;
            
                                return data.data;
                            }
                        },
                        columnDefs: columnDefs,
                        select: isCheck ? 'multi' : '',     
                    });
            
                    return table;
                } 
            }

            For exporting, I used DataTables export button with its button set from Datatables button.js file.

            But , it exported whole data in the list. Not my selected rows.

  9. Hi,

    There is the problem with the library. If the ajax response is in format (standard format when we use column names):

    {"data":[{"id":1,"Name":"Test"},{"id":2,"Name":"Test1"}]}

    Number of selected rows is always 1, also, tbl header checkbox doesn’t turn into indeterminate (when selectAllPages is false). 

    Your library probably expect reposnse without column names (array object), and that is the problem

    Regards,

    Nikola

          1. I didn’t notice that. It works great now. Thank you for your help and plug-in, this is something that jQuery datatables is really needed!

  10. Hello Michael,

    Thanks for the great plugin. Currently I have a functionality were users can edit text in the content of the cell. Every time multiple edits are made, I need to invalidate the rows so the search functionality is able to detect the changes i.e. .rows().invalidate().draw();

    I noticed when this is done, the text at the bottom of the table which lets you know how many rows are selected stops to work. So if even if multiple rows are selected the text still says one row selected. How do I fix this issue. Thanks!

    1. Resolved this issue by specifying ‘data’ in the columnDef config while creating the Datatable e.g.
      columnDefs: [{  targets: 0, searchable: false, data: “ID”}]

  11. Michael,

    1. I have selected 1 row

    2. Next, method “table.ajax.reload()” is executed (server-side processing)

    3. Next, “dataTable.column(0).checkboxes.selected()” is still showing selected row ID from the first step (it should be empty after calling “table.ajax.reload()”)

    Do you have any idea how can i solve this?

    Thanks,

    Nikola

  12. Hi Michael, I really liked the checkbox plugin you created and now I want to know how to add textbox in the data table similar to the checkbox plugin. How to add a checkbox and textbox in the data table with minimum code ? 

  13. Hello Michael, 

    I am using the checkbox plugin you have created and really liked it. However, I am having an issue within my code where I can see the selected row count when clicking on checkbox. I can see the count ONLY when I select the entire row. These are files what I have included, can you please tell me if I miss anything?

    My jQuery DataTables is 1.10.21
    jquery.dataTables.min.js
    dataTables.bootstrap4.min.js
    dataTables.checkboxes.min.js
    jquery-3.5.1.min.js
    bootstrap-4.5.min.js

Leave a Reply

(optional)

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