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. Wow! Thank you very much for this article ! Handling checkbox in server side datatable is always tricky, and your solution is really easy and clear.

  2. Than you for the very helpful tutorial, the best I found on that topic. I’ve a question though, regarding Ajax call on form submit .

    I’m trying to pass the call on form submit like below, but it always gets skipped,

    $.ajax({
       type: "POST",
       url: "delete.php",
       data: {ids: rowId, uid: uid},			
       success: function() {
          alert(done);
       },
       error: function() {
          alert("something went wrong");
       },
       async: false
    });
    

    I even tried placing the above code within table.rows function since the rowId is not available outside, same result, the call is ignored.

    1. Use the code below to retrieve and send IDs of selected row via Ajax. See this jsFiddle for code and demonstration.

      var data = [];
      
      // Iterate over all selected rows
      table.rows({ selected: true }).every(function(index){
         // Get and store row ID
         data.push(this.data()[0]);
      });
      
      // Submit data via Ajax
      $.ajax({
         type: "POST",
         url: "delete.php",
         data: data
      });
      
      // Prevent actual form submission
      e.preventDefault();
      
  3. Thanks for the post. It is really the easiest way to understand how datatables work with select plugin and its API.
    Awesome example. The only problem I’m having is that the first time the id[] (array of hidden inputs) gets items duplicated.
    I noticed this and then did a e.preventDefault() and console.log(id) and did multiple form submits. From 2nd to nth submit, items were not duplicated.

  4. Thank you very helpful, but I have a problem. I’m working in the server-side mode and when I change the page I lose the selection.
    Any idea?

  5. Hi everyone I have 2 problems.

    First is that for me the select and deselect is not a function:

     // Handle click on "Select all" control
       $('#example thead').on('click', 'input[type="checkbox"]', function(e) {
          if (this.checked) {
             table.rows({ page: 'current' }).select();
          } else {
             table.rows({ page: 'current' }).deselect();
          }
         e.stopPropagation();
       });
    

    Second:
    I would like to ask, how can I get only the salary data for the selected rows? Only the amount, the value without the column and ID information.

      1. I’ve got:
        http://code.jquery.com/jquery-latest.min.js
        http://cdn.datatables.net/1.10.11/js/jquery.dataTables.js
        http://cdn.datatables.net/1.10.11/css/jquery.dataTables.css
        And it doesn’t work. But your previous version of thes arcicle : http://www.gyrocode.com/articles/jquery-datatables-checkboxes/ works just great.

        Could you answer my secound question?
        How can I get only the salary data for the selected rows? Only the amount, the value without the column and ID information.

        1. You’re not including Select extension, that’s why select() doesn’t work. Previous article didn’t use Select extension. To get data for salary only, you can use something like table.column(6, { selected: true }).data().

      1. In my tests on server side, if you clicked “select all”, it would only select all for that page. If you paged to the next page, those wouldn’t be selected. For my purpose, the select all needed to select all rows on all pages.

      2. There are two aspects of your code which don’t appear to work with server side. Brian has covered off the first, which is being able to select all rows, not just those visible when you click on the Select All option. His amendment works, and I have combined your 1.0.1 with his amendment and I can get this to work, whilst retaining the change you made to 1.0.1.

        But the second problem remains, and it is this. If I call up the first 10 records, and select 2 of them, the “select-info” div is populated with “2 records selected”. But when I go to the second page (ie records 11-20), the select-info div is now blank again, although if I navigate back to records 1-10, the two I selected are still marked as selected. But if you want to select multiple records over multiple screens this is a big problem as you have no idea how many you have selected. Furthermore, If you click on the “Select All” the count in the info-select is only the number of records on the page when you clocked “Select All”.

        Your otherwise wonderful solution just needs tweaking to enable this functionality to work for serverSide, as it clearly does when using non serverSide JSON data.

  6. Hi Micheal,

    I just wanted to thank you very much for this code and this article you have written. I really love using jQuery DataTables and this enhancement will make it a better library to use!

    Regards,
    James

  7. Hi,

    Great addon to DataTables. I would like to know how I can mark some checkboxes as selected when the page loads?

    Regards,
    Frederik

    1. Frederik, that is a really good question. You may need to provide a state of each checkbox in a separate data field. See this example for demonstration on how each checkbox could be selected based on data in another field. Please note that I have updated the add-on to 1.0.1 in order to make this possible in initComplete callback. I will think on how this could be simplified further.

  8. Hi how about enabling and disabling submit button according to checkboxes status? So when I didn’t select any submit button will be disabled and when I select atleast one, it will be enabled. Can it be done?

      1. It doesn’t work when using server-side processing mode. Checkboxes only in first page are checked.

      2. $p=I('post.start');
        $draw = I('post.draw');
        $length=I('post.length');
        $count=$m->count();
        $list=$m->limit($p.','.$length)->order('id desc')->select();
        

        A page has ten items.

      1. When I select submit button I want to see all data in selected row, not only id number. Example: “1”,”Tiger Nixon”,”System Architect”,”Edinburgh”, “5421”, “2011/04/25″,”$320,800” … Can it be done? Thanks…

        1. If the data is read-only and is coming from the server, you can retrieve the rest of the fields by using ID only. Otherwise if you want to allow editing of the fields, you need to use input elements, something like in this example.

  9. My row is selected/deselected when I click anywhere on the row. But I have two columns that have hyperlinks.
    How to avoid to modify row selection when we click on a hyperlink from these cells ?

  10. my solution is not working when we have the dataTables.select.js Extension.
    Can someone help me to find a solution to not update row selection when we click on a cell that have a link inside ?

    1. the final solution is to update the dataTables.select.js file and add the below code in the enableMouseSelection feature inside the .on( ‘click.dtSelect’, selector, function ( e ) {..}

      // Ignore clicks on hyperlink
      if (e.target.tagName == “A”) {
      return;
      }

      1. Updating the plug-in is always a bad idea. Use something like shown below to prevent click event to propagate to parent elements.

        $('#example tbody').on('click', 'a', function(e){
           e.stopPropagation();
        });
        
      1. Great thanks, you’re right! Main fix is to map column with checkbox to row id:

         
                    columns: [
                        {data : 'id'},
                        ...
                    ],
        
                    select: {
                        style: 'multi'
                    },
        
                    columnDefs: [
                        {
                            targets: 0,
                            checkboxes: {
                                selectRow: true
                            }
                        },
                        ...
                  ]
        

        Thanks to quick answer! Your plugin is universal, my bad 🙂

          1. Btw, does plugin possible can save all checked data (not only id) ? Is exists more easy way than


            var datatable = $("table").DataTable({
            ....
            createdRow: function (row, data, index) {
            window.loadedData[data.id] = data;
            },
            ...
            });
            var allCheckedData = lodash.map(datatable.column(0).checkboxes.selected(), function(id){return window.loadedData[id]})

            П.С. Благодарю за помощь, Михаил!

  11. Can you please provide server-side selection examples? I have problem if i using checkboxes inside columnDefs, the checkboxes appear but the ‘selected rows’ not changing when the rows are selected, always only showed 1 row selected.

      1. OMG i didn’t realize if those checkboxes used an ID to identify the uniqueness of each row . and hey thanks so so much for this awesome plugin 🙂 .

        also is it possible to use the saved selected rows with Print/PDF plugin? im trying to, but it doesn’t load the selected row from another page to show on exported datas. any help would be appreciated

  12. Hi,

    I like your plugin, but I have an issue when having quite a few rows (1000 or so). When using the “select all”, it takes too long for all the checkboxes to be checked. Is this a known issue, and/or can it be solved?

Leave a Reply

(optional)

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