Create A Datatable In A Simple Way

Introduction

 
DataTables is a powerful Javascript library for adding interaction features to HTML tables. This article demonstrates how to create a DataTable instance and load the dynamic data to it.
 

Installing Javascript / CSS

 
The key part of the installation of DataTable involves including the DataTable's Javascript and CSS files. The CSS file is actually optional, but it provides default styling for your table.
 
The required files can be installed in a number of different ways,
  1. Using the DataTable's CDN
  2. Locally
  3. Using package manager (NPM)
CDN 
  1. <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">  
  2.     
  3. <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>  
Local installation
  1. <link rel="stylesheet" type="text/css" href="/DataTables/datatables.css">  
  2.    
  3. <script type="text/javascript" charset="utf8" src="/DataTables/datatables.js"></script>  
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
  1. npm install datatables.net    # Core library  
  2. npm install datatables.net-dt # Styling  
Add HTML
 
For DataTables to be able to enhance an HTML table, the table must be valid, well formatted HTML, with a header (thead) and a single body (tbody). An optional footer (tfoot) can also be used.
  1. <table id="dtExample" class="display">  
  2.     <thead>  
  3.         <tr>  
  4.             <th>Column 1</th>  
  5.             <th>Column 2</th>  
  6.         </tr>  
  7.     </thead>  
  8.     <tbody>  
  9.         <tr>  
  10.             <td>Row 1 Data 1</td>  
  11.             <td>Row 1 Data 2</td>  
  12.         </tr>  
  13.         <tr>  
  14.             <td>Row 2 Data 1</td>  
  15.             <td>Row 2 Data 2</td>  
  16.         </tr>  
  17.     </tbody>  
  18. </table>  
Note that DataTables can actually generate the thead and tbody for you, along with all of the rows and cells of the table, if you are using Ajax sourced data, but for the moment we'll focus on plain HTML.
 
Please also note that while DataTables supports colspan and rowspan in the table's header and footer, they are not supported in the table's tbody and must not be present.
 
Initialising DataTables
 
We've got the HTML table we want to enhance, and we've got all the software and styles we need.
  1. $(document).ready( function () {  
  2.     $('#dtExample').DataTable();  
  3. } )  
DataTables will add ordering, searching, paging and information to your table by default, giving your end users the ability 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 dataTable plugin to enable/ disable them in our table. 
 
Some commonly using options/ features are
  1. paging - To enable pagination
  2. ordering- To enable Sorting
  3. info- It will display the Number of records available in each page
  4. language - To display custom text rather than default
  5. columnDefs- It nothing but Column Definition. To set properties for each column as we wish
  6. Scroll X& Y- Set Scroll for width & Height
  7. Column Rendering- To display not only the text in the td, but also we can render any HTML elements like checkbox, dropdownlist in the dataTable 
Events 
 
We have events to catch the datatable changes.
  1. Order
  2. Search
  3. Page 
  1. $('#dtExample')  
  2.         .on( 'order.dt',  function () { alert( 'Order' ); } )  
  3.         .on( 'search.dt'function () { alert( 'Search' ); } )  
  4.         .on( 'page.dt',   function () { alert( 'Page' ); } )  
  5. .DataTable();  
DataSources
 
DataTables can obtain data from four different fundamental sources:
  1. HTML document (DOM)
  2. Javascript (array / objects)
  3. Ajax sourced data(client-side)
  4. Ajax sourced data(server-side)
We are going to see how to work with Javascript sourced data in dataTables
 
Setup a container in HTML 
  1. <div>  
  2.     <table width="100%" id="dtExample" class="display " cellspacing="0">  
  3.         <thead>  
  4.             <tr>  
  5.                 <th>S.No</th>  
  6.                 <th>Name</th>  
  7.                 <th>Age</th>  
  8.                 <th>City</th>  
  9.                 <th>State</th>  
  10.             </tr>  
  11.         </thead>  
  12.     </table>  
  13. </div>  
Note
The table headers mentioned above should match the table data which we going to see.We added  5 columns here.
 
Create dataTable Instance 
  1. $(document).ready(function () {  
  2.      fnLoadDataTableInstance()  
  3.  })  
  4.  function fnLoadDataTableInstance() {  
  5.      var dataSource = [  
  6.          { name: 'Gowtham', age: 28, city: 'Coimbatore', state: 'Tamil Nadu' },  
  7.          { name: 'Sudhan', age: 38, city: 'Ooty', state: 'Tamil Nadu' },  
  8.          { name: 'Vignesh', age: 34, city: 'Erode', state: 'Tamil Nadu' },  
  9.          { name: 'CSK', age: 34, city: 'Coimbatore', state: 'Tamil Nadu' },  
  10.          { name: 'Arvind', age: 28, city: 'Coimbatore', state: 'Tamil Nadu' },  
  11.          { name: 'Rahul', age: 38, city: 'Ooty', state: 'Tamil Nadu' },  
  12.          { name: 'Raji', age: 34, city: 'Erode', state: 'Tamil Nadu' },  
  13.          { name: 'Ananthi', age: 34, city: 'Coimbatore', state: 'Tamil Nadu' },  
  14.      ]   
  15.        
  16.      $('#dtExample').DataTable({  
  17.          dom: 'Bfrtip',  
  18.          data: dataSource,  
  19.          columns: [  
  20.              {  
  21.                  render: function (data, type, row, meta) {  
  22.                      return meta.row + meta.settings._iDisplayStart + 1;  
  23.                  }  
  24.              },  
  25.              { data: 'name' },  
  26.              { data: 'age' },  
  27.              { data: 'city' },  
  28.              { data: 'state' }  
  29.          ],  
  30.   
  31.          "paging"true,  
  32.          "info"true,  
  33.          "language": {  
  34.              "emptyTable""No data available"  
  35.          },  
  36.          "fnRowCallback"function (nRow, aData, iDisplayIndex) {  
  37.              $("td:first", nRow).html(iDisplayIndex + 1);  
  38.              return nRow;  
  39.          },  
  40.      })  
  41.  }  
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)
 
data --> json data
 
columns --> columns should match the table headers as we mentioned above
 
paging/ordering/info --> to enable those features or not 
 
language- emptyTable --> message to display when data is empty
 
fnRowCallBack --> to display serial number in first columns of each row
 
Output 
 
Create DataTable In A Simple Way
 
Some coding part to work with dataTables
 
To check whether DataTable instance is available or not before we proceed with any operations to it,
  1. if($.fn.DataTable.isDataTable('#dtExample')){  
  2.    alert('dataTable exist')  
  3. }  
To read dataTable & its data,
  1. var dataTable = $('#dtExample').DataTable()  
  2. var data = dataTable.rows().data()  
To get the particular row values,
  1. var dataTable = $('#dtExample').DataTable()  
  2. var dataTableRow = dataTable.row('#' + id).data()  
To update a particular row and redraw the DataTable,
  1. var dataTable = $('#dtExample').DataTable()    
  2. var dataTableRow = dataTable.row('#' + id).data()   
  3. if(dataTableRow){  
  4.     dataTableRow['name'] = 'ManiKandan'  
  5.     dataTable.row('#' + id).data( dataTableRow ).draw()  
  6. }  
To destroy a DataTable,
  1. if($.fn.DataTable.isDataTable('#dtExample')){  
  2.     $('#dtExample').DataTable().destroy()  
  3. }  
To add a row in dataTable
  1. To add single row- dataTable.row.add(addRow).draw() //addRow should be single object
  2. To add multiple rows - dataTable.rows.add(addRow).draw() //addRow should be a array of objects
  1. var dataTable = $('#dtExample').DataTable()  
  2. var addRow = {  
  3.     name: 'Parvati',  
  4.     age: '42',  
  5.     city: 'Dindugul',  
  6.     state: 'Tamil Nadu'  
  7. }  
  8. dataTable.row.add(addRow).draw()  
To remove a row in DataTable,
 
To remove single row- '#id'
 
To remove multiple row- ['#id1', '#id2', '#id3']
  1. var dataTable = $('#dtExample').DataTable()    
  2. var rowsToRemove = ['#id1''#id2''#id3']  
  3. dataTable.rows(rowsToRemove).remove().draw()  
To remove all the rows,
  1. $('#dtExample').DataTable().rows().remove().draw()  
To find row index,
  1. var dataTable = $('#dtExample').DataTable()  
  2. var rowIndex = dataTable.row($(td).closest('tr')).index()  

Summary 

 
In this article, I discussed how we can create datatable using the DataTables plugin. To Edit & Update the rows we need the paid license in dataTable.js. But still we can achieve inLine editing and inCell editing in jQuery.