Powerful Data Table Plugin For JavaScript & jQuery - Datatable.js

File Size: 27.9 KB
Views Total: 1750
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Powerful Data Table Plugin For JavaScript & jQuery - Datatable.js

A data table is one of the most important and useful elements for a website that wishes to display any type of information in an easy-to-read, user-friendly and quickly way. 

With the help of the datatable.js JavaScript library, you can easily generate a feature-rich data table that supports any data type such as static HTML table, JS arrays, JS objects, and Ajax JSON data. It's also a powerful JavaScript datatable plugin that takes away all the hassle of building your own pagination, filtering, and sorting engine. Compatible with both jQuery and Vanilla JavaScript.

How to use it:

1. Download and load the Datatable.js plugin's files in the document.

<!-- Vanilla JS -->
<link rel="stylesheet" href="css/datatable.min.css" />
<script src="js/datatable.min.js"></script>

<!-- jQuery -->
<link rel="stylesheet" href="css/datatable.min.css" />
<script src="js/datatable.min.js"></script>
<script src="/path/to/cdn/jquery.min.js"></script>
<script src="js/datatable.jquery.min.js"></script>

2. Create an empty pagination container next to your HTML table.

<table class="table">
  <thead>
    ... table header ...
  </thead>
  <tbody>
    ... table body ...
  </tbody>
</table>
<!-- Pagination Links Will Be Placed Here -->
<div id="myPagi"></div>

3. Call the function on the HTML table and the plugin will take care of the rest.

// Vanilla JavaScript
var myTable = new DataTable(document.querySelector('.table'), {

    // number of entries per page
    pageSize: 10,

    // enable SORT on specific columns
    sort: [true, true, false],

    // enable FILTER on specific columns
    filters: [true, false, 'select'],
    
    // selector of pagination control
    pagingDivSelector: "#myPagi",

});

// jQuery
$('.table').datatable({

  // number of entries per page
  pageSize: 10,

  // enable SORT on specific columns
  sort: [true, true, false],

  // enable FILTER on specific columns
  filters: [true, false, 'select'],
  
  // selector of pagination control
  pagingDivSelector: "#myPagi",
    
});

4. Not only stactic HTML table, the plugin works with any data type as follows:

var myTable = new DataTable(document.querySelector('.table'), {
    data: [
      ['jQuery', 'Script'],
      ['Google', 'Com'],
      ['Facebook', 'Com']
    ]
});

// OR
var myTable = new DataTable(document.querySelector('.table'), {
    data: [
      {firstname: 'jQuery', lastname: 'Script'},
      {firstname: 'Google',  lastname: 'Com'},
      {firstname: 'Facebook', lastname: 'Com'}
    ]
});

// OR AJAX (JSON) Data
var myTable = new DataTable(document.querySelector('.table'), {
    data: {
      // path to the service
      url: "/path/to/get",

      // post or get
      type: "post", 

      // total amount of data to load, 
      size: null,  

      // determine whether to load all data in one AJAX call
      allInOne: false, 

      // set to a positive value to refresh the data every X milliseconds
      refresh: false,
    }
});

5. All default options & callback functions to customize the data table.

var myTable = new DataTable(document.querySelector('.table'), {
    /**
     * Specify whether the type of the column should be deduced or not. If this option
     * is true, the type is not deduced (mainly here for backward compatibility).
     *
     * @see dataTypes
     */
    forceStrings: false,

    /**
     * Specify the class of the table.
     *
     */
    tableClass: 'datatable',

    /**
     * Specify the selector for the paging div element.
     *
     */
    pagingDivSelector: '.paging',

    /**
     * Specify the class for the paging div element.
     *
     */
    pagingDivClass: 'text-center',

    /**
     * Specify the class for the paging list element.
     *
     */
    pagingListClass: 'pagination',

    /**
     * Specify the class for the paging list item elements.
     *
     */
    pagingItemClass: '',

    /**
     * Specify the class for the paging list link elements.
     *
     */
    pagingLinkClass: '',

    /**
     * Specify the href attribute for the paging list link elements.
     *
     */
    pagingLinkHref: '',

    /**
     * Specify the tabindex attribute for the paging list link elements when
     * disabled.
     *
     */
    pagingLinkDisabledTabIndex: false,

    /**
     * Specify the selector for the counter div element.
     *
     * @see counterText
     */
    counterDivSelector: '.counter',

    /**
     * Specify the selector the loading div element.
     *
     * @see data
     */
    loadingDivSelector: '.loading',

    /**
     * Sepcify the sort options.
     *
     * @type boolean|string|Array|Object
     */
    sort: false,

    /**
     * Specify the default sort key.
     *
     * @type boolean|int|string.
     */
    sortKey: false,

    /**
     * Specify the default sort directions, 'asc' or 'desc'.
     *
     */
    sortDir: 'asc',

    /**
     * Specify the number of columns, a value of -1 (default) specify
     * the the number of columns should be retrieved for the <thead>
     * elements of the table.
     *
     */
    nbColumns: -1,

    /**
     * Specify the number of elements to display per page.
     *
     */
    pageSize: 20,

    /**
     * Specify the number of pages to display in the paging list element.
     *
     */
    pagingNumberOfPages: 9,

    /**
     * Specify the way of identifying items from the data array:
     *
     *   - if this option is false (default), no identification is provided.
     *   - if a Function is specified, the function is used to identify:
     *         function (id, item) -> boolean
     *   - if an int or a string is specified, items are identified by the
     *     value corresponding to the key.
     *
     * @type boolean|int|string|Function.
     *
     */
    identify: false,

    /**
     * Callback function when the table is updated.
     *
     */
    onChange: function (oldPage, newPage) { },

    /**
     * Function used to generate content for the counter div element.
     *
     */
    counterText: function (currentPage, totalPage,
                           firstRow, lastRow,
                           totalRow, totalRowUnfiltered) {
        var counterText = 'Page ' + currentPage + ' on ' + totalPage
            + '. Showing ' + firstRow + ' to ' + lastRow + ' of ' + totalRow + ' entries';
        if (totalRow != totalRowUnfiltered) {
            counterText += ' (filtered from ' + totalRowUnfiltered + ' total entries)';
        }
        counterText += '.';
        return counterText;
    },

    /**
     * Content of the paging item pointing to the first page.
     *
     */
    firstPage: '&lt;&lt;',

    /**
     * Content of the paging item pointing to the previous page.
     *
     */
    prevPage: '&lt;',

    /**
     *
     */
    pagingPages: false,

    /**
     * Content of the paging item pointing to the next page.
     *
     */
    nextPage: '&gt;',

    /**
     * Content of the paging item pointing to the last page.
     *
     */
    lastPage: '&gt;&gt;',

    /**
     * Specify the type of the columns:
     *
     *   - if false, the type is not deduced and values are treated as strings.
     *   - if true, the type is deduced automatically.
     *   - if an Array is specified, the type of each column is retrieve from the
     *     array values, possible values are 'int', 'float' <> 'double', 'date' <> 'datetime',
     *     false <> true <> 'string' <> 'str'. A function can also be specified to convert
     *     the value.
     *
     * @see forceStrings
     *
     */
    dataTypes: true,

    /**
     * Specify the filter options.
     *
     */
    filters: {},

    /**
     * Specify the placeholder for the textual input filters.
     */
    filterText: 'Search... ',

    /**
     * Specify the placeholder for the select input filters.
     */
    filterEmptySelect: '',

    /**
     *
     */
    filterSelectOptions: false,

    /**
     *
     */
    filterInputClass: 'form-control',

    /**
     *
     */
    filterSelectClass: 'form-control',

    /**
     * Callback function before the display is reloaded.
     *
     */
    beforeRefresh: function () { },

    /**
     * Callback function after the display has been reloaded.
     *
     */
    afterRefresh: function () { },

    /**
     * Function used to generate the row of the table.
     *
     */
    lineFormat: function (id, data) {
        var res = document.createElement('tr');
        res.dataset.id = id;
        for (var key in data) {
            if (data.hasOwnProperty(key)) {
                res.innerHTML += '<td>' + data[key] + '</td>';
            }
        }
        return res;
    }
});

// OR
var myTable = new DataTable(document.querySelector('.table'), {
    data: [
      {firstname: 'jQuery', lastname: 'Script'},
      {firstname: 'Google',  lastname: 'Com'},
      {firstname: 'Facebook', lastname: 'Com'}
    ]
});

// OR AJAX (JSON) Data
var myTable = new DataTable(document.querySelector('.table'), {
    data: {
      // path to the service
      url: "/path/to/get",

      // post or get
      type: "post", 

      // total amount of data to load, 
      size: null,  

      // determine whether to load all data in one AJAX call
      allInOne: false, 

      // set to a positive value to refresh the data every X milliseconds
      refresh: false,
    }
});

// jQuery
$('.table').datatable({

  // number of entries per page
  pageSize: 10,

  // enable SORT on specific columns
  sort: [true, true, false],

  // enable FILTER on specific columns
  filters: [true, false, 'select'],
  
  // selector of pagination control
  pagingDivSelector: "#myPagi",

});

6. API methods.

// refresh the data table
myTable.refresh();

// destroy the plugin
myTable.destroy();

// set an option
myTable.option(OptionName, Value);

// load the specified page
myTable.page(number);

// get the current page number
myTable.page();

// reset all filters
myTable.reset-filters();

// retrieve all the element
myTable.select();

// retrieve the first element found with the specified ID
myTable.select(ID);

// retrieve a filtered set of elements
myTable.select(FUNCTION);

// add more data to the data array
myTable.insert(Element/[E1, E2, ...]);

// update the first element found with the specified ID with the new specified data
myTable.update(ID, Element);

// delete the first element found with the specified ID otherwise
myTable.delete(ID);

// delete all the element matching the specified function if a function is specified
myTable.delete(FUNCTION);

This awesome jQuery plugin is developed by Holt59. For more Advanced Usages, please check the demo page or visit the official website.