jQuery DataTables: Row selection using checkboxes and Select extension

Announcement
March 12, 2017
We’ve identified an issue with a plug-in that affects the performance when working with large datasets and released a preliminary fix. However it may not be ready for production just yet and require some further testing.

Please download the latest version from GitHub and please leave a comment if you discover something unusual.

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 for more examples and documentation.

Related posts

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. Thanks for the very nice extension. My question is about the JSON format. I use PHP code to get my database’s values using this function fwrite($file,json_encode(array($rows), JSON_PRETTY_PRINT));

    And the file I get is this. What is the best way to make it proper JSON format?

    [
        [
            {
            "0": "1",
            "ID": "1",
            "1": "Orhan",
            "Name": "Orhan",
            "2": "Hill",
            "Surname": "Hill",
            "3": "Student",
            "Job": "Student",
            "4": "2017-02-16 18:34:39",
            "Date": "2017-02-16 18:34:39",
            "5": "",
            "Picture": ""
            }
        ]
    ]
    
    1. I’ve improved it. But i still don’t know how to replace innermost curly brackets to square brackets. Thanks in advance.

      {
          "data": [
              {
                  "ID": "1",
                  "Tanim": "Orhan",
                  "Marka": "Erece",
                  "Aciklama": "Example",
                  "Tarih": "2017-02-16 18:34:39",
                  "Resim": ""
              }
          ]
      }
      
    2. I’ve improved it. But i still don’t know how to replace innermost curly brackets to square brackets and remove column names. Thanks in advance.

      {
      “data”: [
      {
      “ID”: “1”,
      “Name”: “Orhan”,
      “Surname”: “Hill”,
      “Job”: “Student”,
      “Date”: “2017-02-16 18:34:39”,
      “Picture”: “”
      }
      ]
      }

  10. Oh my dear!
    I solved it. For mysql, to fetch only objects, the code must be “mysqli_fetch_row”. and then to write the JSON format file one can use this command fwrite($file,json_encode(array(‘data’=>$rows), JSON_PRETTY_PRINT));
    Then you get the same format in this plugin. Thank you for the answer and again for this great extension.

  11. 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.

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

  13. 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!

  14. 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;
            }
       }
    

Leave a Reply

You may use simple HTML to add links or lists to your comment. Also use <pre><code class="language-*">...</code></pre> to mark up code snippets. We support language-js, language-markup and language-css for comments.
(Optional)