Useful jQuery DataTables Examples For Beginners

jQuery DataTables is a very progressive enhancement for the jQuery that allows to add advanced interaction controls to any HTML table on your web page. Well good thing is that the jQuery Datatables plugin is absolutely free to use and modify.

Features for jQuery datatables are included: jQuery UI ThemeRoller support, scrolling options for the viewport, display data from almost any data source and smart handling of column widths.

This article related to jQuery datatables plugin, we’ll share some jQuery datatables examples. Don’t worry, these things regarding jQuery datatables are very handy.

jQuery DataTables Examples and Tutorials

How to render column with DataTables

$(document).ready(function() {
    $('#example').dataTable( {
        "aoColumnDefs": [
            {

                "mRender": function ( data, type, row ) {
                    return data +' '+ row[3];
                },
                "aTargets": [ 0 ]
            },
            { "bVisible": false,  "aTargets": [ 3 ] },
            { "sClass": "center", "aTargets": [ 4 ] }
        ]
    } );
} );

How to fire custom events with jQuery DataTables

function eventFired( type ) {
    var n = document.getElementById('demo_info');
    n.innerHTML += ':'+type+' event - '+new Date().getTime()+
    '<:/div>:';
    n.scrollTop = n.scrollHeight;      
}

$(document).ready(function() {
    $('#example')
        .bind('page',   function () { eventFired( 'Page' );
         })
        .bind('filter', function () { eventFired( 'Filter' ); 
         })
        .bind('sort',   function () { eventFired( 'Sort' ); 
         })
        .dataTable();
} );

How to save state with local storage

$(document).ready(function() {
    $('#example').dataTable( {
        "bStateSave": true
    } );
} );

How to set defaults for DataTables

$(document).ready(function() {
    $.extend( $.fn.dataTable.defaults, {
        "bFilter": false,
        "bSort": false
    } );

    $('#example').dataTable();
} );

How to control sorting direction for jQuery DataTables

$(document).ready(function() {
    $('#example').dataTable( {
        "aoColumns": [
            null,
            { "asSorting": [ "asc" ] },
            { "asSorting": [ "desc", "asc", "asc" ] },
            { "asSorting": [ "desc" ] },
            null
        ]
    } );
} );

How to use a callback function to format a specific row

$(document).ready(function() {
    $('#example').dataTable( {
        "fnRowCallback": function( nRow, aData, iDisplayIndex ) 
           {
            /* Append the grade to the default row class name */
            if ( aData[4] == "A" )
            {
                $('td:eq(4)', nRow).html( 'A' );
            }
        },
        "aoColumnDefs": [ {
                "sClass": "center",
                "aTargets": [ -1, -2 ]
        } ]
    } );
} );

How to group rows with jQuery DataTables

$(document).ready(function() {
    oTable = $('#example').dataTable({
        "fnDrawCallback": function ( oSettings ) {
            if ( oSettings.aiDisplay.length == 0 )
            {
                return;
            }

            var nTrs = $('#example tbody tr');
            var iColspan = nTrs[0].
                      getElementsByTagName('td').length;
            var sLastGroup = "";
            for ( var i=0 ; iip'
    });
} );

How to sort and detect type with jQuery DataTables

jQuery.fn.dataTableExt.aTypes.unshift(
    function ( sData )
    {
        var sValidChars = "0123456789-,";
        var Char;
        var bDecimal = false;

        /* Check the numeric part */
        for ( i=0 ; i y) ?  1 : 0));
};

jQuery.fn.dataTableExt.oSort['numeric-comma-desc'] 
          = function(a,b) {
    var x = (a == "-") ? 0 : a.replace( /,/, "." );
    var y = (b == "-") ? 0 : b.replace( /,/, "." );
    x = parseFloat( x );
    y = parseFloat( y );
    return ((x < y) ?  1 : ((x > y) ? -1 : 0));
};

$(document).ready(function() {
    $('#example').dataTable();
} );

How to sort DOM live

$.fn.dataTableExt.afnSortData['dom-text'] 
      = function  ( oSettings, iColumn )
      {
            return $.map( oSettings.oApi._fnGetTrNodes(oSettings), 
                                  function (tr, i) {
            return $('td:eq('+iColumn+') input', tr).val();
      } );
}

$.fn.dataTableExt.afnSortData['dom-select'] = 
      function  ( oSettings, iColumn )
      {
        return $.map( oSettings.oApi._fnGetTrNodes(oSettings), 
           function (tr, i) {
             return $('td:eq('+iColumn+') select', tr).val();
          } );
}

$.fn.dataTableExt.afnSortData['dom-checkbox'] = 
    function  ( oSettings, iColumn )
    {
     return $.map( oSettings.oApi._fnGetTrNodes(oSettings), 
         function (tr, i) {
          return $('td:eq('+iColumn+') input', tr).
                 prop('checked') ? '1' : '0';
       } );
}

/* Initialise the table with the required column sorting data types */
$(document).ready(function() {
    $('#example').dataTable( {
        "aoColumns": [
            null,
            null,
            { "sSortDataType": "dom-text" },
            { "sSortDataType": "dom-text", "sType": "numeric" },
            { "sSortDataType": "dom-select" },
            { "sSortDataType": "dom-checkbox" }
        ]
    } );
} );

How to add a new row dynamically with jQuery datatables

var giCount = 1;

$(document).ready(function() {
    $('#example').dataTable();
} );

function fnClickAddRow() {
    $('#example').dataTable().fnAddData( [
        giCount+".1",
        giCount+".2",
        giCount+".3",
        giCount+".4" ] );

    giCount++;
}

How to apply regular expression filtering

function fnFilterGlobal ()
{
    $('#example').dataTable().fnFilter(
        $("#global_filter").val(),
        null,
        $("#global_regex")[0].checked,
        $("#global_smart")[0].checked
    );
}

function fnFilterColumn ( i )
{
    $('#example').dataTable().fnFilter(
        $("#col"+(i+1)+"_filter").val(),
        i,
        $("#col"+(i+1)+"_regex")[0].checked,
        $("#col"+(i+1)+"_smart")[0].checked
    );
}

$(document).ready(function() {
    $('#example').dataTable();

    $("#global_filter").keyup( fnFilterGlobal );
    $("#global_regex").click( fnFilterGlobal );
    $("#global_smart").click( fnFilterGlobal );

    $("#col1_filter").keyup( function() { fnFilterColumn( 0 ); 
     } );
    $("#col1_regex").click(  function() { fnFilterColumn( 0 ); 
    } );
    $("#col1_smart").click(  function() { fnFilterColumn( 0 ); 
    } );

    // ... etc for the other four columns
} );

How to submit form elements with jQuery datatables

var oTable;

$(document).ready(function() {
    $('#form').submit( function() {
        var sData = oTable.$('input').serialize();
        alert( "The following data submitted to the server: \n\n"+sData );
        return false;
    } );

    oTable = $('#example').dataTable();
} );

How to toggle (hide and show) columns dynamically

$(document).ready(function() {
    $('#example').dataTable( {
        "sScrollY": "200px",
        "bPaginate": false
    } );
} );

function fnShowHide( iCol )
{
    var oTable = $('#example').dataTable();

    var bVis = oTable.fnSettings().aoColumns[iCol].bVisible;
    oTable.fnSetColumnVis( iCol, bVis ? false : true );
}
Duan Lingxin

Duan Lingxin

Content crafter and chief editor at Scratching Info. Also regular contributor on other major online tech platforms. Security Specialist by day and a writer by night, he does his best to instill his knowledge about tech while delivering inspiring and life changing resources through his writing,

More Posts - Website

Leave a Comment