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. Hi, nice plugin. I Have two questions/feature requests though.

    Is it possible to
    a) put the check-all box in the footer (as well) and
    b) use custom markup for the checkboxes? render in columnDefs does not seem to work.

    Thanks for your reply

  2. I have lots of old datatables settings that were written for version 1.9. My question is does this solution still work if I change your sample datatables init setting to legacy 1.9 settings?

    1. Not sure exactly what you mean. My extension requires jQuery DataTables 1.10 or above. However jQuery DataTables 1.10 is backward compatible with legacy settings written for jQuery DataTables 1.9. If you’re using jQuery DataTables 1.9, see if you can upgrade without breaking anything.

  3. Hello,
    Thanks for the great extension, I’d like to know if there’s any chance I can make the row selectable only when you click on the checkbox and not everywhere in the row.

    Thanks in advance

  4. Hello,
    great Extension.
    I really struggle at getting to work multiple Tables with multiselect in one form and after tweaking nearly a week i really wonder if it is possible at all, i tried it like this (based on some helpers on StackOverflow):

    	datatable =  $('.table_select').DataTable( {
    		'initComplete': function(){
    		var api = this.api();
    		 api
    			.rows()
    				.every(function(){
    			   var data = this.data();
    			   if(data[1] === '1'){
    				  api.cells(this.index(), 0).checkboxes.select();
    			   }
    			});
    		},
    		order: [[2, "asc"]],
    		paging:false,
    		info:false,
    		filter:false,
    		language: {
    			"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/German.json",
    		},
    		columns: [
    			null,
    			{ "visible": false},
    			null
    		],
    		'columnDefs': [{
    			'targets': 0,
    			'checkboxes': {
    				'selectRow': true,
    				'selectAll': false
    			}
    		}],
    		select: {
    			style: 'multi'
    		}
    	}); 
    	
    	let table = datatable.data();
    	flen = table.length;
    
    	/*for(var i = 0; i < flen; i++)
    	{
    		var acc = [];
    		
    		$.each(table[i], function(index, value){
    		{
    			acc.push(index + ': ' + value + '');
    		}
    		});
    		var pre = document.createElement('pre');
    		pre.innerHTML = acc;
    		document.body.appendChild(pre)
    	}*/
    	
    	$('.select_table_form').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(
    				 $('')
    					.attr('type', 'hidden')
    					.attr('name', 'select_values[]')
    					.val(rowId)
    			 );
    		  });
    	});
    

    I still only get the data from the first table.

  5. Hi there, first i would like to thank you for this amazing plugin, it saved me a lot of time. i was using it on codeigniter php frame work , although it took me some time tweaking and geting to work i managed to get to the values from the database and get selected values. but i was not able to save the selected items to a single column. if you could give me some tips it would mean a lot

    thanks in advance 🙂

  6. I am interested in a slightly different variation. I would like to have checkboxes in the row, but if you click on the checkbox in the header, instead of checking or unchecking all the checkboxes, it filters the table for rows where the checkbox is checked (or clears that filter on unchecking) I have developed a solution which will do that (basically hiding “nearest” tr if attr(“checked”) is checked – it works but it does not reflected in the dom info (e.g. that will still say “Showing 10 of 300 rows” when in fact your only seeing 3 “checked” rows)

    1. David, that is possible to do using custom filters that either include or exclude selected rows. Then info section will say something like “Showing 1 to 4 of 4 entries (filtered from 300 total entries)”. This example with custom filters can give you an idea of how it may work. I’m available for hire and can implement it for you, please contact me if interested. Thanks!

  7. is inline edit is possible in this example?
    and i want to store selected row data to the database.
    is it possible to add inputbox on selected column (ex.salary column will be input type). and send selected row data to the database.

  8. i show this https://datatables.net/examples/api/form.html example but it does not have multi selection.
    my requirements:
    1.multiple selection
    2.form inputs
    3.only selected row data should be store in database.
    4.i don’t know javascript and jquery much. so how can i store serialized data into php variable? i want this data in php variable because i have to perform insert query.
    *CAN YOU PLEASE MAKE EXAMPLE LIKE ABOVE REQUIREMENTS
    Thank You!!

  9. Hello, It is very nice plugin. Thanks.
    I just wonder how i send/post selected items to php script when you click submit button to send selected items as an e-mail with that php script.

  10. working good for me not using “serverSide”: true
    can we make it work with “serverSide”: true, and “processing”: true

  11. Great plugin!

    I’ve been trying to track down a memory leak (12,000 rows) and narrowed it down to this plugin. Good to see that you guys are working on it – looking forward to the update!

    1. Thanks! Just released a preliminary update improving performance with large datasets. Can you please download the latest code from GitHub and test it with your system? Thanks!

      Also besides not properly detaching events on table destroy, I wasn’t able to find any other memory leaks.

    1. Thanks for posting the example, unfortunately it doesn’t have Datatable properly initialized and no 50000 rows. You may be seeing data that hasn’t been picked by garbage collector yet. See this post on memory leaks. By using Record Allocation Timeline profiling tool in Chrome I wasn’t able to see memory leaks unless I’m doing something wrong.

      1. Thanks for the quick replies!

        I just tried it with Chrome 54 on Windows and you’re right – both cases work fine!

        Previously I was using Chrome 56 on Linux. Pretty sure I’ll still see the issue there, but that’s something to investigate…. I’ll report back.

        1. Thank you for the effort! With that many rows have you considered using server-side processing mode? I’m sure your page will be very slow if you do searching, sorting or other operations with 50,000 rows.

          1. Yes, we have considered server-side, but most of our customers do not have so many rows – it’s just one in particular that is really pushing the limits. Believe it or not searching is fine, it’s just the destroy() you take a hit on.

            We’ve decided to forego checkboxes for now, and re-evaluate in in a few months. Although a few Chrome versions did not have the leak shown above (as you found), most did, and Firefox did. We’ll just stay with the Datatables.select plugin 1.1 for now. Thanks again!

  12. hello sir,

    i wanna get id on event of submit button but there is some problem…i don’t know what it is. my code is as below. please check it and reply me as soon as possible..

    java script code :-

    
    $(document).ready(function(){
        $('#cid').on('change',function(){
            var chID1 = $(this).val();
         	
    		var table =  $('#employee-grid').DataTable( {
    			   	destroy: true,
    				processing: true,
    				serverSide: true,
                                    ajax:({
    				type: 'POST',
    				data:{chid:chID1},
    				url:'ajaxData1.php',
    			 	dataType: 'JSON',
    				
    			 // json datasource
    				}),
    				
    				columnDefs: [
           						  {
    					            targets: 0,
    					            checkboxes: {
    				                				selectRow: true
                								}
             					   }
          						],
          			'select': {
             						'style': 'multi'
          					}
          			
    				});	
    		 });
    	  $('#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(
                 $('')
                    .attr('type', 'hidden')
                    .attr('name', 'q_id[]')
                    .val(rowId)
             );
          });
       });
    });
    

    Php script :

    
       if(isset($_POST['sb']))
       {
    	$qid=$_POST['q_id'];
    	foreach($qid as $a)
    	{
    	    echo $a;
            }
       }
    
  13. Hi Team,

    I am facing performance issue.I have 1000 + rows in my datatable and we are using IE browser. Please suggest if anything for this.

      1. Hi Michael,

        As mentioned i added the below 2 files from latest code.
        dataTables.checkboxes.min.ja and dataTables.checkboxes.css

        Performance is better then previous code. But still its taking some couple of seconds to select all rows. Anything that i am missing that needs to add.

        Thanks,
        Pritesh Sahni

        1. Hi Michael,

          We have a edit button on screen. This edit button is enable only when user select the single row or multiple rows to update the data and display information is also displayed correctly.
          I.e. the no of rows selected count is perfect.

          Once data updated we are calling table.ajax.reload(); and data also refreshed but display information is not getting updated. Its still showing the previous selected rows count and when we refresh the page its gone.

          I debug little bit and found that after reload below function is getting called showInfoSelected: function(){
          and previous display information are coming from this function.

          After reload i would like to remove the selected-item information only. Please suggest.

          Thanks,
          Pritesh Sahni

            1. Hi Micheal,

              Calling table.draw() is not updating the display information. This is the same case when we have table.ajax.reload() and you fixed that . To avoid table.ajax.reload() we have tried to simply call the table.draw() it refresh the data but it shows the previous selected rows count.

              Actually we are using data table editor plugin now which when receive the response from the server refresh the data table but as it was not updating the display selected information.We tried to call the table.draw() in ajax success but this is also not working. Please assist.

              Thanks,
              Pritesh Sahni

              1. Apparently I have introduced an error with yesterday’s update. I added another fix to reset selected rows when ajax.reload() was called in client-side processing mode and state saving wasn’t enabled, please see this example. After you click “Reload” button, the state should be cleared as expected.

                1. Hi Michael,

                  Thanks for the update. From where i can download the latest code?
                  Can you please provide me link.

                  Pritesh Sahni

                  1. You can download the latest code from GitHub, or use this direct link. Files are also hosted in the cloud and could be added to your HTML page in the head section using the code below.

                    <link type="text/css" href="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.6/css/dataTables.checkboxes.css" rel="stylesheet" />
                    <script type="text/javascript" src="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.6/js/dataTables.checkboxes.min.js"></script>
                    
                    1. Hi Michael,
                      i ahve just tested with latest code. Its working but issue is ajax.reload() again call the ajax that i do not want hi have the updated data from the editor plugin response. I just to refresh the table so that selected rows reset.Is that possible?

                      Thanks,
                      Pritesh Sahni

  14. Hi Michael,
    How would I go about getting the value of a specific cell of a selected row, instead of the row Id?

    Thanks,
    Kevin

    1. Kevin, it is a good question.

      If you use Select extension and client-side processing mode, the code below will get full data for selected rows.

      var data = table.rows({ selected: true }).data();

      See this example for code and demonstration.

      If you don’t use Select extension, it would be more complex. If you use server-side processing mode, it is not currently possible but the solution could be available.

      1. Thanks Michael.

        When doing this in my project it returns me all rows in the data array. Everything’s the same as in your example, except it not being ajax data. Is there anything else to be careful about?

        $(document).ready(function() {
           var table = $('#table').DataTable({
              'columnDefs': [
                 {
                    'targets': 0,
                    'checkboxes': {
                       'selectRow': true
                    }
                 }
              ],
              'select': {
                 'style': 'multi'
              },
              'order': [[1, 'asc']]
           });
           
           // Handle form submission event 
           $('#print-form').on('submit', function(e){
              var form = this;
        
        	  var data = table.rows({ selected: true }).data();
              console.log(data);
        
              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(
                     $('')
                        .attr('type', 'hidden')
                        .attr('name', 'id[]')
                        .val(rowId)
                 );
              }); [...]
          1. Oops, sorry for the confusion. I meant it’s returning me all rows even though I only select one for example

      1. Hi Michael,

        I have downloaded the latest code to enable row selecting using shift key and tested its working fine. But i saw one thing, we have a edit button to edit rows. When user click on Edit button we have a bootstrap modal which shows the list of columns to update. On save button we hide the pop-up and refresh the grid by ajax call table.ajax.reload().
        but once this refresh is done after 2-3 seconds we can see the selected rows are getting unchecked and un highlighted not sure what is the root cause.

        Thanks,
        Pritesh Sahni

          1. Hi Michael,
            Thanks for the info.
            Michael we have a new requirement with datatable. We do not want to use global or individual column serach of datatable. Instead we want 2 dropdown on top of the table. From first dropdown user can select the column and based on the selected column second dropdown should get populated with the values and this should be multiselect and when user select the values from this dropdown and hit submit button it should refresh the datatable. Let me know, if any of this kind of pluign is available or any reference.

            Thanks,
            Pritesh

  15. Hi Michael,

    I am using columns to assign data to my rows, I added the columnDef so that I can have the checkbox in my table but there’s no checkbox showing up. Instead it’s displaying the value of DT_Rowid. If I change the { “data”:”DT_RowId”} to { “data”:””}
    datatables throws an error “table id=selectDealers – Requested unknown parameter ” for row 0″. And if I simply remove it, there is still no checkbox showing and dealerCode is being displayed on the first column. Can you tell me what I’m doing wrong? Thanks a lot.

      
    var table = $('#selectDealers').DataTable({
    		"ajax": "trans_get_dealerdata.php",
    		scrollCollapse: true,
    		'columnDefs': [{
    			'targets': 0,
    			'searchable': false,
    			'orderable': false,
    			'className': 'dt-body-center',
    			'checkboxes':{
    				'selectRow': true
    			},
    			'select':{
    				'style':'multi'
    			}
    		}],
    		"columns": [
    			{ "data":"DT_RowId"},
    			{ "data":"dealerCode"},
    			{ "data":"lastName"},		
    			{ "data":"firstName"},			
    			{ "data":"dealerLevel"}				
            ]
    	});
    

Leave a Reply

(optional)

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