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 really like this and so does my boss. When I check the select all it works fine for all pages and I can see that by paging through and looking. If I go to page 2 and select a couple of boxes and then go back to page 1 and click my button I am not getting those values. I call a function on button click called SubAll(). I did change the way I get the boxes which is most likely the issue…and #2 when I send the array to my controller method the data is empty, what am I missing? TIA.

    
         var values = [];
    
                $('#timesheet').find('input[type="checkbox"]:checked').each(function (index, rowId) {
                    //this is the current checkbox
                    var temp = $(this).closest('tr').attr('id');
    
                    if (String(temp) === String("undefined")) {
                        //skip; it is the select all box
                    }
                    else {
                        //push to array
                        values.push({ ID: temp });
                    }
                });
    
  2. Hi There,
    I’m facing issues while trying to check checkboxes on page load.
    Scenario – My table loads with the page and also the data in it is added in the jsp page only.After that when i initialise the datatable and use ‘createdCell’ event to check the checkboxes. it gives me an error –
    Uncaught TypeError: Cannot read property ‘isCellSelectable’ of undefined
    at s. (dataTables.checkboxes.min.js:5)
    at s.iterator (jquery.dataTables.min.js:96)
    at s. (dataTables.checkboxes.min.js:5)

    I tried to debug the issue and found that the event is called before the cell is converted into a checkbox as in the function input ‘td’ was – data while when i do the same for a table which is created at runtime the ‘td’ was already converted to a checkbox and had the content –

    I’m not sure if i was able to explain the issue properly, please do give it a look if you could understand.
    Here’s my code –
    JSP –

    
    
    
    #
    SAP ID
    Batch
    Employee Name
    
    
    
    
    
    ${employee.sap_id}
    ${employee.sap_id}
    ${employee.batch_name}
    ${employee.first_name} ${employee.last_name}
    
    
    
    
    

    and JS –

    
    $('#emptable').DataTable({
    	"lengthMenu" : [ [ 5, 10, 20, 30, -1 ], [ 5, 10, 20, 30, "All" ] ],
    	'columnDefs': [{
    		'targets': 0,
    		'checkboxes': {'selectRow': true},
    		'createdCell': function (td, cellData, rowData, row, col){
    			if($("#selected_employees").val().includes(cellData)){
    				this.api().cell(td).checkboxes.select();
    			}
    		}
    	}],
    	'select': {'style': 'multi'},
    	'order': [[1, 'asc']]
    });
  3. When using this code the data is undefined

    $('#Table1').dataTable({
                    'initComplete': function (settings) {
                        var api = this.api();
    
                        api.cells(
                           api.rows(function (idx, data, node) {
                               return (data[1] === 'LU 29/04/2019') ? true : false;
                           }).indexes(),
                           0
                        ).checkboxes.select();
                    },
    
    1. I don’t see a problem with your code. Using callback function as a row selector became only possible in DataTables 1.10.3, check the version that you’re using. Also make sure you’re using array of arrays as your data, and not array of objects. If possible, can you create an example demonstrating the issue on jsFiddle or similar service?

  4. Hey Michael, thx for all your work, it’s really good, but I have one question for u,

    if I already put all data in table(the DOM), how can I selected one checkbox?

    I tried “this.api().cell(td).checkboxes.select();”

    it’s not working, return undefined.

    for some reason I can’t open jsfiddle.net, so I have to ask u here. thx u.

  5. Hey Michael can we disable select all option in table header ? Also will it work fine if I use dialog modal to display datatable ? Please update me if I need to add any additional css ( like Jquery UI ) when using this inside dialog.

  6. Clicking checkbox with large sets of data will cause delay/lag before check appears. Almost 500ms.

    1. Thank you for your comment. I have added a new page demonstrating current level of performance, please see Performance. Plugin handles 1000 records well, but with 5000 records there is a delay when “Select All” control is clicked. Selecting individual checkboxes in all examples does not cause a delay. There is definitely a room for improvement.

  7. Implemented jQuery DataTables Checkboxes. I have 22 rows to display. Clicking on the “Select All” checkbox worked in that the checkboxes in every row across all pages (3 pages) were checked. However the “Select All” checkbox did not have the little dash image in it. Instead it had contained a check mark, and at the bottom of the Datatable it stated “1 row selected” where it should have stated “22 rows selected”‘.

      1. I don’t understand. What do you mean a column containing checkboxes need to have unique data in it? How does a column that has a checkbox in the same column in every contain unique data? I have defined the column per your solution using className:”select-checkbox”. Can you please clarify. Thank you.

          1. I understand now. What was throwing me off was that all of your and everybody else’s examples had a checkbox column as the first column in the table. In my scenario my first column was not a checkbox column, instead, the last column of my table is the checkbox column but the first column contained unique values. So I just duplicated the first column in the table in the last column of the table that is the checkbox column and it appears to be working fine. Thank you for the clarification.

  8. Michael: I see that your checkboxes API sets the checkbox as checked / unchecked whenever a row is clicked on.
    That is to say that when anywhere in a given row the row is clicked on (any column) the checkbox becomes checked or unchecked. Is there a property to set so that this does not happen? I don’t want the checkbox checked or unchecked whenever the user clicks anywhere (any column) in the row. I only want the checkbox checked or unchecked when the user specifically checks the checkbox in a given row. Thank you. Gary

      1. Michael: Thank you. I have implemented both solutions you have provided. In both solutions the DataTable shows “x row(s) selected” at the bottom of the table when you click on a row, in any column. That is fine, however is it possible for that little “x row(s) selected” message to only generate when a row checkbox is clicked and not just any column of a row? I certainly apologize it this looks like I am going in circles here. Please advise and thanks again for your assistance.

      2. …Another thing I noticed is that when I use the two solutions you suggested, then a JQurey ‘click” handler I coded which looks like:
        $(‘#myTableName’).on(‘click’, ‘tbody input[type=”checkbox”]’, function(e){…})
        …does not work, however this JQuery click handler does work when I configure columnDefs as:
        ‘targets’: 9,
        ….
        ‘checkboxes’: {
        ‘selectRow’: true
        }
        Your thoughts?
        thank you

  9. Hi Michael:
    with fowlling code, I can not get selected value at IE browser, chrome browser is ok.
    At IE browser, DataTable().column(0).checkboxes.selected() return a array that not include current clicked checkbox’s state and value)

  10. Hello: According to the JQuery Datatables Server-side processing page:

    https://legacy.datatables.net/usage/server-side

    … the text states: “….When using server-side processing, DataTables will make an XHR request to the server for each draw of the information on the page (i.e. when paging, sorting, filtering etc)….”

    I understand this is from an older version of JQuery Datatables. However my question is: If I were to update to the latest version of JQuery Datables and also bring in your CheckBoxes API, will your CheckBoxes code retain the state of what checkboxes were checked, even when the DataTables API keeps going back to the server every time the user pages, sorts and filters, as stated, for each draw?

    Thank you
    Gary

    1. Yes, Checkboxes plug-in retains data between requests, please see server-side processing example.

      With server-side processing mode you need to remember that Checkboxes plug-in is not aware of data manipulation on the server side. For example, if you check a box and then press a button to delete the row on the server and then refresh the table, Checkbox plug-in is not aware that the row has been deleted and will still keep checked row ID in the internal list. So in this case you need to either uncheck the box before sending request to delete the record on the server, or treat the list of selected IDs as if there might be some that are no longer exist.

  11. For AJAX url, is it only accept JSON format?

    
    var table = $('#example').DataTable({
          'ajax': 'https://api.myjson.com/bins/1us28',
    

    Is it possible if I retrieve data directly select from a table MySQL? I’ve tried it using Codeigniter framework and got some errors:

    “DataTables warning: table id=checkboxTables – Requested unknown parameter ’10’ for row 0, column 10. For more information about this error, please see http://datatables.net/tn/4

    Then, selected rows count (bottom bar) is going wrong, always count: 1

  12. Hi! First, thanks for a great extension plugin for datatables.
    I wonder if there is any solution of sorting items i tables by checkbox? in other words all checked rows on Init should be sorted and visible on first page of datatable.

    Something like this; https://jsfiddle.net/s65tjv0v/8/
    (I cant get this to work in my solution)

    Thanks in advance

    1. Thanks! Internally plug-in disables ordering and searching which I need to tweak to allow customization like this. Alternatively, see this example where you can show selected rows or not selected rows using API, although this works in client-side processing mode only.

  13. Hi!

    First, thanks for a great extension plugin for datatables.
    And sry for my bad english

    I have an array of previously selected user values
    And I need to initialize the checkboxes in the table from this array

    Now I ‘m doing it in the event initComplite

    ....
    initComplete: function () {
    var api = this.api();
    
    api.cells(selected_rows, 0).checkboxes.select();
    }
    

    But the problem is that the table contains 4k entries
    And an array selected_rows about 2,3k
    This code works for about 30 seconds

    How to do it correctly?

  14. I tried following this but the checkboxes on the first column are not showing. The first column is a unique ID. What am I doing wrong?

            $('#tblCases').DataTable({        
                "ajax":
                {
                    "url": "/GetData/",
                    "data": { id: 123},               
                },
                "columnDefs": [
                    {
                        "targets": 0,
                        "checkboxes": true
                    }
                ],          
                order: [[1, "asc"]]                      
            });
    
  15. thanks for the check box code. works great.
    one problem i’m having, when i have fixed header in datatables and scroll the page the check all does not work.

    any help would be appreciated.

    thank you

    1. works with fxed header when scroll is all the way up or all the way down. when scroll is half way check all does not work.

  16. Hi,
    I have a table with 3 columns of checkboxes. For each row, I want to do some input validation to check that only 1 out of 3 checkboxes are checked. How can I do that?

Leave a Reply

(optional)

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