Create a datatable in JQuery

Introduction

DataTables is a powerful Javascript library for adding interaction features to HTML tables. This article demonstrates creating a DataTable instance and loading the dynamic data.

Installing Javascript/CSS

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 required files can be installed in several different ways,

  1. Using the DataTable's CDN
  2. Locally
  3. Using package manager (NPM)

CDN 

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">  
    
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js">
</script>  

Local installation

<link rel="stylesheet" type="text/css" href="/DataTables/datatables.css">  
   
<script type="text/javascript" charset="utf8" src="/DataTables/datatables.js"></script>  

NPM packages

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  

How to Add HTML?

For DataTables to enhance an HTML table, the table must be valid, well-formatted HTML with a header (thread) and a single body (tbody). An optional footer (tfoot) can also be used.

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

Note that DataTables can generate the thread 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 all the software and styles we need.

$(document).ready( function () {  
    $('#dtExample').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,

  1. paging- To enable pagination.
  2. ordering- To enable Sorting.
  3. info- It will display the number of records available on each page.
  4. language- To display custom text rather than the default.
  5. columnDefs- It is 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 and dropdownlist in the dataTable.

Events 

We have events to catch the datatable changes.

  1. Order
  2. Search
  3. Page 
$('#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:

  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

How to Setup a container in HTML?

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

Note

The table headers mentioned above should match the table data we will see. We added  5 columns here.

Create dataTable Instance 

$(document).ready(function () {  
     fnLoadDataTableInstance()  
 })  
 function fnLoadDataTableInstance() {  
     var dataSource = [  
         { name: 'Gowtham', age: 28, city: 'Coimbatore', state: 'Tamil Nadu' },  
         { name: 'Sudhan', age: 38, city: 'Ooty', state: 'Tamil Nadu' },  
         { name: 'Vignesh', age: 34, city: 'Erode', state: 'Tamil Nadu' },  
         { name: 'CSK', age: 34, city: 'Coimbatore', state: 'Tamil Nadu' },  
         { name: 'Arvind', age: 28, city: 'Coimbatore', state: 'Tamil Nadu' },  
         { name: 'Rahul', age: 38, city: 'Ooty', state: 'Tamil Nadu' },  
         { name: 'Raji', age: 34, city: 'Erode', state: 'Tamil Nadu' },  
         { name: 'Ananthi', age: 34, city: 'Coimbatore', state: 'Tamil Nadu' },  
     ]   
       
     $('#dtExample').DataTable({  
         dom: 'Bfrtip',  
         data: dataSource,  
         columns: [  
             {  
                 render: function (data, type, row, meta) {  
                     return meta.row + meta.settings._iDisplayStart + 1;  
                 }  
             },  
             { data: 'name' },  
             { data: 'age' },  
             { data: 'city' },  
             { data: 'state' }  
         ],  
  
         "paging": true,  
         "info": true,  
         "language": {  
             "emptyTable": "No data available"  
         },  
         "fnRowCallback": function (nRow, aData, iDisplayIndex) {  
             $("td:first", nRow).html(iDisplayIndex + 1);  
             return nRow;  
         },  
     })  
 }  
  • 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 the serial number in the first columns of each row

Output 

Create DataTable In A Simple Way

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 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
var dataTable = $('#dtExample').DataTable()  
var addRow = {  
    name: 'Parvati',  
    age: '42',  
    city: 'Dindugul',  
    state: 'Tamil Nadu'  
}  
dataTable.row.add(addRow).draw()  

To remove a row in DataTable,

  1. To remove a single row- '#id'
  2. To remove multiple row- ['#id1', '#id2', '#id3']
var dataTable = $('#dtExample').DataTable()    
var rowsToRemove = ['#id1', '#id2', '#id3']  
dataTable.rows(rowsToRemove).remove().draw()  

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()  

Summary 

In this article, I discussed how to 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.