Installing Datatable
The key part of installing DataTable involves including the DataTable's Javascript and CSS files. The CSS file is optional but provides default styling for your table.
The installation can be performed in several different ways,
- Using the DataTable's CDN
- Local Installation by including from local folders
- Using package manager (NPM)
Using the DataTable's CDN
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.7/css/jquery.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js">
</script>
Local Installation by including from local folders
<link rel="stylesheet" type="text/css" href="/DataTables/datatables.css">
<script type="text/javascript" charset="utf8" src="/DataTables/datatables.js"></script>
Using package manager (NPM)
DataTables and its extensions are available as NPM packages. The package base name is datatables.net, and the extensions and styling integration options are available as individual packages
npm install datatables.net # Core library
npm install datatables.net-dt # Styling
Datatable Initilisation
The table html code be like for eg:-
<div>
<table width="100%" id="dtExample" class="display " cellspacing="0">
<thead>
<tr>
<th>S.No</th>
<th>Name</th>
<th>Age</th>
<th>City</th>
<th>State</th>
</tr>
</thead>
</table>
</div>
Here the id provided dtExample will be used for datatable loading and stuffs.
Now you have to add a Js script like:-
$(document).ready( function () {
$('#dtExample').DataTable();
} )
This will make the basic initilisation of datatable.
DataTables will add ordering, searching, paging, and information to your table by default, allowing your end users to find the information they want as quickly as possible.
If you want to customize your DataTable, this can be done by specifying configuration parameters in an object passed to the DataTable() function.
Configure DataTable
We have in-built options and features in the dataTable plugin to enable/ disable them in our table.
Some commonly used options/features are,
paging- To enable pagination.
ordering- To enable Sorting.
info- It will display the number of records available on each page.
language- To display custom text rather than the default.
columnDefs- It is nothing but Column Definition. To set properties for each column as we wish.
Scroll X& Y- Set Scroll for width & Height.
Column Rendering- To display not only the text in the td but also we can render any HTML elements like checkbox and dropdownlist in the dataTable.
This we configure in dom property
$('#dtExample').DataTable({
dom: 'Bfrtip',
});
dom- Bfrtip is B - Buttons, f - filtering input, r - processing display element, t - table, i - informational panel, p - pagination control (if need these controls, then add the alphabet to the dom else remove)
Events
We have events to catch the datatable changes.
$('#dtExample')
.on( 'order.dt', function () { alert( 'Order' ); } )
.on( 'search.dt', function () { alert( 'Search' ); } )
.on( 'page.dt', function () { alert( 'Page' ); } )
.DataTable();
DataSources
DataTables can obtain data from four different fundamental sources:
- HTML document (DOM)
- Javascript (array/objects)
- Ajax sourced data(client-side & server side)
We are going to see how to work with Javascript-sourced data in dataTables
HTML document (DOM)
<table id="dtExample" class="display">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 Data 1</td>
<td>Row 1 Data 2</td>
</tr>
<tr>
<td>Row 2 Data 1</td>
<td>Row 2 Data 2</td>
</tr>
</tbody>
</table>
In this method we use table data as normal as we use in other instance. Datatable will use the row data here to process our different requests.
Javascript (array/objects)
Html Code
<table width="100%" id="dtExample" class="display " cellspacing="0">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
<th>State</th>
</tr>
</thead>
</table>
$(document).ready(function () {
LoadDataTableInstance()
})
function LoadDataTableInstance() {
var dataSource = [
{ name: 'Rohit', age: 28, city: 'Coimbatore', state: 'Tamil Nadu' },
{ name: 'Virat', age: 38, city: 'Ooty', state: 'Tamil Nadu' },
{ name: 'Sachin', age: 34, city: 'Erode', state: 'Tamil Nadu' },
{ name: 'Ravindra', age: 34, city: 'Coimbatore', state: 'Tamil Nadu' },
{ name: 'Ronaldo', age: 28, city: 'Coimbatore', state: 'Tamil Nadu' },
{ name: 'Messi', age: 38, city: 'Ooty', state: 'Tamil Nadu' },
{ name: 'Maradona', age: 34, city: 'Erode', state: 'Tamil Nadu' },
{ name: 'Pele', age: 34, city: 'Coimbatore', state: 'Tamil Nadu' },
]
dt_table_editor =$('#dtExample').DataTable({
dom: 'Bfrtip',
data: dataSource,
columns: [
{ data: 'name' },
{ data: 'age' },
{ data: 'city' },
{ data: 'state' }
],
buttons: [
{extend: "create", editor: dt_table_editor,className: 'btn btn-sm btn-primary btn-new'},
{extend: "edit", editor: dt_table_editor,className: 'btn btn-sm btn-primary btn-edit'},
{extend: "remove", editor: dt_table_editor,className: 'btn btn-sm btn-primary btn-delete'}
],
"paging": true,
"info": true,
"language": {
"emptyTable": "No data available"
}
})
}
dom: as explained earlier
data- json data
columns- columns should match the table headers, as we mentioned above
buttons- created, edit and delete buttons
paging/ordering/info- to enable those features or not
language- emptyTable- message to display when data is empty
Ajax sourced data
Here in datasource, the data will be fetched using ajax requests. Rest all will be same.This data can be loaded from client side ajax request or from serverside generated data.
dt_table_editor = $('#dtExample').DataTable({
dom: 'Bfrtip',
ajax: {
url: "/module/controller/action",
type: "POST"
},
serverSide: true,
columns: [
{ data: 'name' },
{ data: 'age' },
{ data: 'city' },
{ data: 'state' }
],
buttons: [
{extend: "create", editor: dt_table_editor,className: 'btn btn-sm btn-primary btn-new'},
{extend: "edit", editor: dt_table_editor,className: 'btn btn-sm btn-primary btn-edit'},
{extend: "remove", editor: dt_table_editor,className: 'btn btn-sm btn-primary btn-delete'}
],
"paging": true,
"info": true,
"language": {
"emptyTable": "No data available"
}
})
If its from serverside you have to put serverside variable to true.
Some coding parts of working with dataTables
To check whether the DataTable instance is available or not before we proceed with any operations on it,
if($.fn.DataTable.isDataTable('#dtExample')){
alert('dataTable exist')
}
To read the dataTable & its data,
var dataTable = $('#dtExample').DataTable()
var data = dataTable.rows().data()
To get the particular row values,
var dataTable = $('#dtExample').DataTable()
var dataTableRow = dataTable.row('#' + id).data()
To update a particular row and redraw the DataTable,
var dataTable = $('#dtExample').DataTable()
var dataTableRow = dataTable.row('#' + id).data()
if(dataTableRow){
dataTableRow['name'] = 'ManiKandan'
dataTable.row('#' + id).data( dataTableRow ).draw()
}
To destroy a DataTable,
if($.fn.DataTable.isDataTable('#dtExample')){
$('#dtExample').DataTable().destroy()
}
To remove all the rows,
$('#dtExample').DataTable().rows().remove().draw()
To find the row index,
var dataTable = $('#dtExample').DataTable()
var rowIndex = dataTable.row($(td).closest('tr')).index()