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. There could be multiple reasons. Most obvious would be that you need to include files jQuery DataTables Checkboxes JS/CSS after jQuery DataTables JS/CSS files. If that doesn’t resolve your issue, please share an example that demonstrates the problem. Thanks!

  1. This, like many pages / examples of a datatable with checkboxes driven with this tooling, announce “x rows selected” in the data table footer.  Mine is not doing that for some reason and as I’ve browsed several examples worth of code trying to find “the magic”, I have been unsuccessful.  So the question is either (1) Why is this syntax not automatically showing up in my DataTables footer or (2) How can I get this syntax to appear?

    1. If you can share some examples publicly or privately (through the contact form), I will be able to give you more information. In general in order to see the “X rows selected”, the following conditions have to be met:

      • Checkbox extension is included and enabled for at least one column.
      • Select extension is included and enabled, see this example.
      • Row selection should be enabled for at least one column with checkboxes.selectRow option, see this example.
      • Table summary panel should be not be hidden (visible by default), see dom option.
      • Item select information in table summary panel should not be disabled (enabled by default), see select.info option.
      1. Michael,

        Ah HA!  That was EXACTLY what I needed.  Well sort of.  I had originally, using demo examples, configured the “selectRow” option so that a checked box styled the row but found, since I use table-striping in my DataTable, I found the adjusted color (the tooling automatically references the “.selected” class) leaves things kind of hideous as you cursor over things…which I did not want.

        So now, while you have solved the problem by explaining that the “x rows selected” is contingent on “selectRow” to do its work, I’m left back were I was.  I basically want to change the CSS for “.selected” so it does not change the color…leaving it EXACTLY how it is so there is no VISUAL indication, but obviously still enabling the reliance on the class being present as the user clicks/unclicks the checkbox.

        I’m ok at CSS, but I don’t see a way to override the class so that is basically does a background-color of “leave it alone”.

        If you have any ideas there, would love the help…meanwhile, I’m removing the table striping which pretty much resolves the issue.  I find that row highlight (plugins) mucks that all up visually pretty badly so I’ll likely have to turn that off too.

        However, you definitely explained away the problem and for that, I’m grateful.

        Mike

  2. Hello, I used datatables fetching data to my database. I want to get the values of the checked rows and save it to the another table. 

  3. Hello, I recently came across this plugin which is pretty cool, just have a few question Here is a test case i came up with: What i noticed when i introduced the plugin is that:

    (1) The hard coded input values i set for each check box is overridden, i don’t want this. is there a way around this ?

    (2) The styling i originally use in the hard coded HTML is also overridden, I don’t want this, I want the original formatting to remain.

    (3) I want to use my own styling for the “select all” check box, is that possible ?

    So all this boils down to is having to add just a select all check box with custom styling, and not changing anything in the html.

  4. hello Michael, im trying to send the data to a controller, but always es empty, but in console works, can you helpme please, whats wrog with my code.

    $('#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)
                        );
                    });
               
                    // Output form data to a console it works
                    //$('#example-console-rows').text(rows_selected.join(","));
     
                       // trying to send array to controller,  dsnt works     
                       $.ajax({
                        url: "@Url.Content("~/RADICACIONES/CerrarMasivo")",
                        type: 'post',
                        data: table.rows({ selected: true }).data().toArray(),
    // tryed this to data: rows_selected,                    
    
    dataType: 'json',
                        success: function (returnedData) {
                            console.log(returnedData);
                        }
                    });
     
                });

  5. Hi Michael,

    I implemented a RoR app where I successfully used datatables. One column has checkboxes, which worked fine. Now I wanted to have a “check all” on the filtered result of the table. After adding the part for dt-checkboxes this was working. 

    Unfortunately the form is no longer posting the checkbox values to the server. Inspecting the checkbox I found no id, or name, or value attribute. 

    What am I doing wrong? 

    Thanks

    // page rendered by RoR
    <input type="checkbox" name="my_column_ids[]" id="my_column_ids_" value="1419" />
    
    // inspected checkbox
    <input type="checkbox" class="dt-checkboxes" autocomplete="off">
    


    // rails application.js 
    
    $( document ).on('turbolinks:load', function() {
      $('#filtered_streams').DataTable( {
        "search": { "regex": true },
        bStateSave: true
      } );
      $('#filtered_analyses').DataTable( {
        "search": { "regex": true },
        "order": [[ 7, "desc" ]],
        bStateSave: true,
        // add for dt-checkboxes
        'columnDefs': [
           {
              'targets': 1,
              'checkboxes': {
                 'selectRow': true
              }
           }
        ],
        'select': {
           'style': 'multi'
        }
      } );
    


    1. this extension replaces all content of the target column. I am also looking for a way to add unique ids and values but im not sure this extension allows for it.

    2. I ended up storing the data i needed in other elements of the table and then adding some data-* attributes to the <td> element after table initiation. Since checkboxes extension provides the selected <td> to the callback function instead of the actual input, it was more convenient to do it this way.

      In the code below I am also switching out all the generated checkboxes with my own custom one. You might be interested in doing something similar.

      table.columns('.tool-column.dt-checkboxes-cell').every( function() {
          $(this.nodes()).each( (index, node) => {
          $(node).attr('data-user', node.parentNode.id);
          $(node).attr('data-tool', this.nodes().column(node._DT_CellIndex.column).header().dataset.tool);
          $(node).html('<div class="chronos-checkbox-container"><input class="dt-checkboxes" type="checkbox"><div class="chronos-checkbox-visible"></div></div>');
         });
      });

  6. Hi, I have applied checkboxes on my jquery datatable. When i tried to select all, it will checked all records but when i processed it, sometimes it will only process some records but not all records that you have checked.

    I uses below codes:

                var detailsList = [];

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

               $.each(rows_selected, function (index, rowId) {

                        var detail = {

                            RowPointer : rowId

                        }

                        detailsList.push(detail);

  7. Hi Michael,

    very cool extension, thanks.

    how to use shift key to select a range of rows? is it plan to support or do you have some hints?

  8. Hi Michael, 

    very cool extension, thanks.

    I’m yanuar from Indonesia, How can i selected all rows automatically on the first show up? 

    1. Yanuar, thanks for your kind words! You can use initComplete callback and call column().checkboxes.select() API method. For example:

      'initComplete': function(settings, json) {
         var api = new $.fn.dataTable.Api(settings);
         api.column(0).checkboxes.select();     
      },
      

      See this example for code and demonstration.

  9. Hi Michael,

    Thanks you for the wonderful free plugin! I am having an odd problem with the checkboxes and it does not occur consistently. Sometime when I am checking a row, it also checks the column heading/check all box instead of just the minus sign in the checkall checkbox.

    Note – the ‘x’ representing a checkmark

    Expected Working results: (can’t add image)

    [ – ]  SKU          Rental LP       (header)

    [   ]  26728       RPL-1             (row)

    [ x ]  26729      RLP-2             (row) // user checks this box and the minus sign adds in the header

    Not Working results: (can’t add image)

    [ x ]  SKU            Rental LP       (header)

    [    ]   6935412   RPL-23           (row)

    [ x ]   6935412   RLP-24          (row) // user checks this box and the a check adds in the header


    I am pulling my data using the browser fetch API. I have this working in another application just fine so I am not sure what I am doing wronge here. 

    Using the cdn:  <script type=”text/javascript” src=”//gyrocode.github.io/jquery-datatables-checkboxes/1.2.12/js/dataTables.checkboxes.min.js”></script>

    which is placed below all of my jquery. 

    Code: 

    async function buildRentalTable(json) {    
        if ($.fn.DataTable.isDataTable('#rentalSearchTable')) {
            $('#rentalSearchTable').DataTable().destroy();
        }
    
        $("#rentalSearchTable").DataTable({
            "destroy": true,
            "data": json,
            "dom": '<"top d-flex justify-content-between pt-2"ip><"top d-flex justify-content-between pt-2"lf><"scroll-body"rt><"bottom d-flex justify-content-between pt-3"ip>',
            "scrollCollapse": true,
            "oLanguage": {
                "sEmptyTable": "No results found",
                "sSearch": "Filter Results:"
            },
            "rowId": "RentalLPID", // this is unique
            "columnDefs": [{
                "targets": [0],
                "orderable": false
            },
            {
                "targets": 0,
                "checkboxes": true,
                "className": "check-row"
            },
            ],
            "order": [[1, 'asc']],
            "columns": [
                { "data": "SKU", "checkboxes": true },           
                {
                    "data": function (data) {
                        return `<a href="" data-sku="${data.SKU}"  class="edit-sku">${data.SKU}</a>`
                    }, "title": "SKU" 
                },
                {
                    "data": function (data) {
                        return `<a href="" data-rentalLP="${data.RentalLPID}"  class="edit-rentalLP">${data.RentalLPID}</a>`
                    }, "title": "Rental LP"
                },
                
                { "data": "ProductName", "title": "Product Name" },
                { "data": "RentalStatus", "title": "Current Status" },
                { "data": "BufferDaysBefore", "title": "Buffer Before" },
                { "data": "BufferDaysAfter", "title": "Buffer After" },
    
            ],      
            "pagingType": "full_numbers",
            "lengthMenu": [
                [10, 25, 50, -1],
                [10, 25, 50, "All"]
            ],
            //responsive: true
        });  
    }

    Thanks for taking a look! 

    Lindsay 

    1. Lindsay, thanks for the detailed description and kinds words! In your second example you have two duplicate SKUs – 6935412 which causes unexpected behavior. Plug-in requires data to be unique in the column containing checkboxes.

      1. Thanks Michael – I was typing out a follow up question back to you, but then found my error.  🙂 

        I am all set! 

        Lindsay

  10. Hey Michael.I would really be glad if you could offer a solution for the problem i am having.

    1.For select all checkbox even if I select a few columns its get checked instead of showing a horizontal line in checkout like in your demo above.

    2.The moment I select even 1 row the select all box checked.Then If I select another row and then deselect one row the select all checkbox becomes empty for some reason. 

Leave a Reply

(optional)

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