Example
Client-side processing mode with Ajax sourced data
Example below shows a table in client-side processing mode where data is received from the server via Ajax request.
$(document).ready(function (){
var table = $('#example').DataTable({
'ajax': {
'url': '/lab/articles/jquery-datatables-how-to-add-a-checkbox-column/ids-arrays.txt'
},
'columnDefs': [{
'targets': 0,
'searchable': false,
'orderable': false,
'className': 'dt-body-center',
'render': function (data, type, full, meta){
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
}],
'order': [[1, 'asc']]
});
// Handle click on "Select all" control
$('#example-select-all').on('click', function(){
// Get all rows with search applied
var rows = table.rows({ 'search': 'applied' }).nodes();
// Check/uncheck checkboxes for all rows in the table
$('input[type="checkbox"]', rows).prop('checked', this.checked);
});
// Handle click on checkbox to set state of "Select all" control
$('#example tbody').on('change', 'input[type="checkbox"]', function(){
// If checkbox is not checked
if(!this.checked){
var el = $('#example-select-all').get(0);
// If "Select all" control is checked and has 'indeterminate' property
if(el && el.checked && ('indeterminate' in el)){
// Set visual state of "Select all" control
// as 'indeterminate'
el.indeterminate = true;
}
}
});
// Handle form submission event
$('#frm-example').on('submit', function(e){
var form = this;
// Iterate over all checkboxes in the table
table.$('input[type="checkbox"]').each(function(){
// If checkbox doesn't exist in DOM
if(!$.contains(document, this)){
// If checkbox is checked
if(this.checked){
// Create a hidden element
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', this.name)
.val(this.value)
);
}
}
});
});
});
In addition to the above code, the following Javascript library files are loaded for use in this example:
//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js
The following CSS library files are loaded for use in this example to provide the styling of the table:
//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.cssHighlights
Javascript
-
Columns definition
'columnDefs': [{ 'targets': 0, 'searchable':false, 'orderable':false, 'className': 'dt-body-center', 'render': function (data, type, full, meta){ return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">'; } }],
Option columnsDef is used to define appearance and behavior of the first column (
'targets': 0
).Searching and ordering of the column is not needed so this functionality is disabled with searchable and orderable options.
To center checkbox in the cell, internal DataTables CSS class
dt-body-center
is used.Option render is used to prepare the checkbox control for being displayed in each cell of the first column. We use a trick with
$('<div/>').text(data).html()
to encode HTML entities that could be present in the data.Another trick here is to give input element a name with square brackets (
id[]
). This will make handling of list of checked checkboxes easier on the server-side. For example, PHP will convert all these parameters to an array, see PHP FAQ: How do I get all the results from a select multiple HTML tag for more information. -
Initial sorting order
'order': [[1, 'asc']],
By default, DataTables sorts the table by first column in ascending order. By using order option we select another column to perform initial sort.
-
“Select all” control
// Handle click on "Select all" control $('#example-select-all').on('click', function(){ // Get all rows with search applied var rows = table.rows({ 'search': 'applied' }).nodes(); // Check/uncheck checkboxes for all rows in the table $('input[type="checkbox"]', rows).prop('checked', this.checked); });
We attach event handler to handle clicks on “Select all” control. To retrieve all checkboxes that are present in the table taking into account currently applied filter, we use rows() method using appropriate selector-modifier.
// Handle click on checkbox to set state of "Select all" control $('#example tbody').on('change', 'input[type="checkbox"]', function(){ // If checkbox is not checked if(!this.checked){ var el = $('#example-select-all').get(0); // If "Select all" control is checked and has 'indeterminate' property if(el && el.checked && ('indeterminate' in el)){ // Set visual state of "Select all" control // as 'indeterminate' el.indeterminate = true; } } });
The purpose of the event handler above is to detect when one of the checkboxes in the table is unchecked when “Select all” control was checked. When that happens, we can set “Select all” control to a special state indeterminate to indicate that only some checkboxes are checked.
-
Form submission
// Handle form submission event $('#frm-example').on('submit', function(e){ var form = this; // Iterate over all checkboxes in the table table.$('input[type="checkbox"]').each(function(){ // If checkbox doesn't exist in DOM if(!$.contains(document, this)){ // If checkbox is checked if(this.checked){ // Create a hidden element $(form).append( $('<input>') .attr('type', 'hidden') .attr('name', this.name) .val(this.value) ); } } }); });
When table is enhanced by jQuery DataTables plug-in, only visible elements exist in DOM. That is why by default form submits checkboxes from current page only.
To submit checkboxes from all pages we need to retrieve them with $() API method. Then for each checkbox not present in DOM we add a hidden element to the form with the same name and value. This allows all the data to be submitted.
It’s even more simple if form submission is performed via Ajax. In that case URL-encoded data for submission can be produced using the code below:
var data = table.$('input[type="checkbox"]').serialize();
For more information on submitting the form elements in a table powered by jQuery DataTables, please see jQuery DataTables: How to submit all pages form data.
Server-side processing
Please note that the example and code above will work for client-side processing mode only.
In server-side processing mode ('serverSide':true
) elements <input type="checkbox">
would exist for current page only. Once page is changed, the checked state of the checkboxes would not be preserved.
See jQuery DataTables Checkboxes for a universal solution that will work for server-side processing mode as well.
If I need to add a column as the last column and need to point to a movie file source,
how can I do that? Help will be appreciated.
Please ask a question on Stack Overflow, tag it
datatables
and I will try to help.Brilliant. Easily modified for an mvc ajax post:
Create a CSV model binder and then you’re working with a List:
That should have been
List<int> keys
This was incredibly helpful, thank you!
Someone have any idea about this error:
Uncaught TypeError: table.rows is not a function
?There could be multiple reasons. You could be using older version of the DataTables 1.9.x or not initializing the table properly. See this jsFiddle for an example of correct code.
This is really helpful.
If we do select all first, then search, then submit, the code will submit all the items in table.
We may need to use search applied nodes in the table for the submit too, not sure whether the check checkbox in DOM in submit method doing the same thing?
If you want to submit only checkboxes from search results, then replace
table.$('input[type="checkbox"]')
with$('input[type="checkbox"]', table.rows({ search: 'applied' }).nodes())
. See this jsFiddle for code and demonstration.How do you get the check boxes to checked state on going from page to page, is this built in to datables or is some thing you added?
No, this is how jQuery DataTables works in the client-side processing mode. I assume it preserves cell nodes and their content.
That’s really helpful thanks a lot. But if we want to fill the table with a request result, how can we do that?
I need to retain the checked values of 1st page wen I come back from 2nd page. Please help me out.
Since it is calling the back end again its not able to retain. How to overcome it?
How to add “how many row selected” in the client side processing ?
Please see jQuery DataTables Checkboxes extension which offers much easier way to add checkboxes and also shows how many checkboxes are selected.
How to skip submitting the checkbox select all value e.g the example_length=50 in this case if the “Show 50 entries” is selected?
How to get sorting on checkbox column for some selected checkbox.
Ascending should get all selected and descending should get all deselected
i AM CONFUSE , where should i write code for Select all check box,
I have multiple table and i want to create one function , which can be called from any table .
Should i create directive or should i create service for that.
I already have table Directive for all table .
great ! 🙂 I need the first and last cols fixed and I added after columnDefs:
but then the checkbox select all doesn’t work, do you have suggestion?
There is a newer jQuery DataTables Checkboxes extension where we just added support for FixedColumns extension. You just need to use “Download” button to download the most recent version or visit the project page on GitHub.
There is a problem with datatables-fixedheader. The select-all checkbox events from fixedheader (not from $tablecontainer) are not handled.
Is there a way to have a checkbox column that is only tied to the current page? For instance, checking the column only checks the checkbox rows on the current page, not all the pages. I would keep the checkbox data in an array or something but this gets very complicated with pagination and variable page lengths. We have something like “All 25 records on this page are selected. Select all 299 records. Clear All selection.” where they can choose the current page only or all pages.
You could modify line 21 using
var rows = table.rows({ 'page': 'current', 'search': 'applied' }).nodes();
Please see jQuery DataTables Checkboxes extension which offers much easier way to add checkboxes and also lets you select checkboxes on the current page only using selectAllPages option.Nice tutorial! I have Error Message “Illegal mix of collations for operation ‘like'” when search about something. My database Collation Is utf8_general_ci. How to fix that? Thanks!
Thanks for the tutorial..
Please help I want to send selected server side row data to php for further processing.
Edes, examples in this, this and this articles illustrate how checkboxes data could be submitted to the server, see
submit
event handler for more details.I tried, but I didn’t know how to pass those data to php script.
My Codes:
$(‘#std_marks’).on(‘submit’, function(e){
var form = this;
// Iterate over all checkboxes in the table
table.$(‘input[type=”checkbox”]’).each(function(){
// If checkbox doesn’t exist in DOM
if(!$.contains(document, this)){
// If checkbox is checked
if(this.checked){
// Create a hidden element
$(form).append(
$(”)
.attr(‘type’, ‘hidden’)
.attr(‘name’, this.name)
.val(this.value)
);
}
}
$.ajax({
type: ‘POST’,
url: ‘php/sms/par_bulksms.php’,
data: $(this).serialize(),
success: function (data)
{
$.each(rows_selected, function(index, rowId){
// Remove hidden element
$(form).children(“input”).remove();
});
});
});
Thank you very much. This tutorial is very helpful!
Thanks Micheal! 🙂 I’m new to JQuery! I wanted to select only one check box at a time in the same script. Can you help me with it.
Although checkboxes are intended for multiple-choice selection you can do so with Checkboxes extension.
Use
select: { style: 'single' }
instead ofselect: { style: 'multi' }
initialization option. You would also need to disable “Select all” control.See this example for code and demonstration.