DataTables logo DataTables

Custom API functions

One of the most common interactions with DataTables for a developer (other than initialisation of the table of course!) is to make use of the API functions provided in the release package. While allowing for a fairly extensive range of code interactions, the default API set can be greatly enhanced by making use of the functions provided below, as suitable for your application.

fnAddDataAndDisplay()
Show details
Add a new row to the table and display it on the screen by jumping the pagination to the required location. This function also returns an object with the added TR element and it's index in aoData such that you could provide an effect (fade for example) to show which row has been added. This function is a drop in replacement for fnAddData with one important exception, it will only take a 1D array, and not 2D (i.e. it will not add multiple rows).
Author: Allan Jardine
Code:
$.fn.dataTableExt.oApi.fnAddDataAndDisplay = function ( oSettings, aData )
{
	/* Add the data */
	var iAdded = this.oApi._fnAddData( oSettings, aData );
	var nAdded = oSettings.aoData[ iAdded ].nTr;
	
	/* Need to re-filter and re-sort the table to get positioning correct, not perfect
	 * as this will actually redraw the table on screen, but the update should be so fast (and
	 * possibly not alter what is already on display) that the user will not notice
	 */
	this.oApi._fnReDraw( oSettings );
	
	/* Find it's position in the table */
	var iPos = -1;
	for( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
	{
		if( oSettings.aoData[ oSettings.aiDisplay[i] ].nTr == nAdded )
		{
			iPos = i;
			break;
		}
	}
	
	/* Get starting point, taking account of paging */
	if( iPos >= 0 )
	{
		oSettings._iDisplayStart = ( Math.floor(i / oSettings._iDisplayLength) ) * oSettings._iDisplayLength;
		this.oApi._fnCalculateEnd( oSettings );
	}
	
	this.oApi._fnDraw( oSettings );
	return {
		"nTr": nAdded,
		"iPos": iAdded
	};
}

/* Example use */
var oTable;
$(document).ready(function() {
	oTable = $('#example').dataTable();
	oTable.fnAddDataAndDisplay( [ 1, 2, 3, 4, 5 /* ... */ ] );
} );
fnAddTr()
Show details
Take a TR element and add it to a DataTables table. Useful for maintaining custom classes and other attributes.
Author: Allan Jardine
Code:
/*
 * Function: fnAddTr
 * Purpose:  Add a TR element to a table
 * Returns:  -
 * Inputs:   object:oSettings - automatically passed by DataTables
 *           node:nTr - TR element to add to table
 *           bool:bRedraw - optional - should the table redraw - default true.
 * Usage:    var row = '<tr class="gradeX"><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>';
				     oTable.fnAddTr( $(row)[0] );
 */
$.fn.dataTableExt.oApi.fnAddTr = function ( oSettings, nTr, bRedraw ) {
	if ( typeof bRedraw == 'undefined' )
	{
		bRedraw = true;
	}
	
	var nTds = nTr.getElementsByTagName('td');
	if ( nTds.length != oSettings.aoColumns.length )
	{
		alert( 'Warning: not adding new TR - columns and TD elements must match' );
		return;
	}
	
	var aData = [];
	for ( var i=0 ; i<nTds.length ; i++ )
	{
		aData.push( nTds[i].innerHTML );
	}
	
	/* Add the data and then replace DataTable's generated TR with ours */
	var iIndex = this.oApi._fnAddData( oSettings, aData );
	oSettings.aoData[ iIndex ].nTr = nTr;
	
	oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
	this.oApi._fnBuildSearchArray( oSettings, 1 );
	
	if ( bRedraw )
	{
		this.oApi._fnReDraw( oSettings );
	}
}
fnDataUpdate()
Show details
Update the internal data for a TR element based on what is used in the DOM. You will likely want to call fnDraw() after this function.
Author: Lior Gerson
Code:
$.fn.dataTableExt.oApi.fnDataUpdate = function ( oSettings, nRowObject, iRowIndex )
{
	var dataRow = oSettings.aoData[iRowIndex]._aData;
	$(nRowObject).find("TD").each( function(i) {
		dataRow[i] = $(this).html();
	} );
}
fnDisplayStart()
Show details
Set the point at which DataTables will start it's display of data in the table.
Author: Allan Jardine
Code:
/*
 * Function: fnDisplayStart
 * Purpose:  Set the display start point
 * Returns:  void
 * Inputs:   object:oSettings - DataTables settings object - NOTE - added automatically
 *           int:iStart - New display start point
 *           bool:bRedraw - Redraw the display based on new start point - optional - default true
 */
$.fn.dataTableExt.oApi.fnDisplayStart = function ( oSettings, iStart, bRedraw )
{
	if ( typeof bRedraw == 'undefined' )
	{
		bRedraw = true;
	}
	
	oSettings._iDisplayStart = iStart;
	oSettings.oApi._fnCalculateEnd( oSettings );
	
	if ( bRedraw )
	{
		oSettings.oApi._fnDraw( oSettings );
	}
}
fnDisplayRow()
Show details
Take a TR element and alter the table's paging to show the TR in question.
Author: Allan Jardine
Code:
$.fn.dataTableExt.oApi.fnDisplayRow = function ( oSettings, nRow )
{
	var iPos = -1;
	for( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
	{
		if( oSettings.aoData[ oSettings.aiDisplay[i] ].nTr == nRow )
		{
			iPos = i;
			break;
		}
	}
	
	if( iPos >= 0 )
	{
		oSettings._iDisplayStart = ( Math.floor(i / oSettings._iDisplayLength) ) * oSettings._iDisplayLength;
		this.oApi._fnCalculateEnd( oSettings );
	}
	
	this.oApi._fnDraw( oSettings );
}

/* Example use */
var oTable;
$(document).ready(function() {
	oTable = $('#example').dataTable();
	oTable.fnDisplayRow( oTable.fnGetNodes()[20] );
} );
fnFakeRowspan()
Show details
Creates rowspan cells in a column when there are two or more cells in a row with the same content, effectively grouping them together visually. Note - this plug-in currently only operates correctly with server-side processing.
Author: Fredrik Wendel
Code:
$.fn.dataTableExt.oApi.fnFakeRowspan = function ( oSettings, iColumn, bCaseSensitive ) {
	/*
	 * Type:        Plugin for DataTables (http://datatables.net) JQuery plugin.
	 * Name:        dataTableExt.oApi.fnFakeRowspan
	 * Requires:    DataTables 1.6.0+
	 * Version:     1.0.1
	 * Description: Creates rowspan cells in a column when there are two or more
	 *              cells in a row with the same content. It only works for 
	 *              server-side processing as cells are removed and can't be 
	 *              sorted by DataTables.
	 *              
	 * Inputs:      object:oSettings - dataTables settings object
	 *              integer:iColumn - the column to fake rowspans in
	 *              boolean:bCaseSensitive - whether the comparison is case-sensitive or not (default: true)
	 * Returns:     JQuery
	 * Usage:       $('#example').dataTable().fnFakeRowspan(3);
	 *              $('#example').dataTable().fnFakeRowspan(3, false);
	 *
	 * Author:      Fredrik Wendel
	 * Created:     2010-02-10
	 * Language:    Javascript
	 * License:     GPL v2 or BSD 3 point style
	 */
	
	/* Fail silently on missing/errorenous parameter data. */
	if (isNaN(iColumn)) {
		return false;
	}
	
	if (iColumn < 0 || iColumn > oSettings.aoColumns.length-1) {
		alert ('Invalid column number choosen, must be between 0 and ' + (oSettings.aoColumns.length-1));
		return false;
	}
	
	var oSettings = oSettings,
		iColumn = iColumn,
		bCaseSensitive = (typeof(bCaseSensitive) != 'boolean' ? true : bCaseSensitive);

	oSettings.aoDrawCallback.push({ "fn": fakeRowspan, "sName": "fnFakeRowspan" });

	function fakeRowspan () {
		var firstOccurance = null,
			value = null, 
			rowspan = 0;
		jQuery.each(oSettings.aoData, function (i, oData) {
			var val = oData._aData[iColumn],
				cell = oData.nTr.childNodes[iColumn];
			/* Use lowercase comparison if not case-sensitive. */
			if (!bCaseSensitive) {
				val = val.toLowerCase();
			}
			/* Reset values on new cell data. */
			if (val != value) {
				value = val;
				firstOccurance = cell;
				rowspan = 0;
			}
			
			if (val == value) {
				rowspan++;
			}
			
			if (firstOccurance !== null && val == value && rowspan > 1) {
				oData.nTr.removeChild(cell);
				firstOccurance.rowSpan = rowspan;
			}
		});
	}
	
	return this;
}
fnFilterAll()
Show details
Apply the same filter to all DataTable instances on a particular page. The function call exactly matches that used by fnFilter() so regular expression and individual column sorting can be used.
Author: Kristoffer Karlström
Code:
$.fn.dataTableExt.oApi.fnFilterAll = function(oSettings, sInput, iColumn, bEscapeRegex) {      
   for (var i in this.dataTableSettings) {
       jQuery.fn.dataTableExt.iApiIndex = i;
       this.fnFilter(sInput, iColumn, bEscapeRegex);
   }
}

/* Example usage */
var oTable;
$(document).ready(function() {
	oTable = $(".dataTable").dataTable();
	
	$("#search").keyup( function () {
		/* Filter on the column (the index) of this element */
		oTable.fnFilterAll(this.value);
	} );
});
fnGetColumnData()
Show details
Return an array of table values from a particular column, with various filtering options..
Author: Benedikt Forchhammer
Code:
(function($) {
/*
 * Function: fnGetColumnData
 * Purpose:  Return an array of table values from a particular column.
 * Returns:  array string: 1d data array 
 * Inputs:   object:oSettings - dataTable settings object. This is always the last argument past to the function
 *           int:iColumn - the id of the column to extract the data from
 *           bool:bUnique - optional - if set to false duplicated values are not filtered out
 *           bool:bFiltered - optional - if set to false all the table data is used (not only the filtered)
 *           bool:bIgnoreEmpty - optional - if set to false empty values are not filtered from the result array
 * Author:   Benedikt Forchhammer <b.forchhammer /AT\ mind2.de>
 */
$.fn.dataTableExt.oApi.fnGetColumnData = function ( oSettings, iColumn, bUnique, bFiltered, bIgnoreEmpty ) {
	// check that we have a column id
	if ( typeof iColumn == "undefined" ) return new Array();
	
	// by default we only wany unique data
	if ( typeof bUnique == "undefined" ) bUnique = true;
	
	// by default we do want to only look at filtered data
	if ( typeof bFiltered == "undefined" ) bFiltered = true;
	
	// by default we do not wany to include empty values
	if ( typeof bIgnoreEmpty == "undefined" ) bIgnoreEmpty = true;
	
	// list of rows which we're going to loop through
	var aiRows;
	
	// use only filtered rows
	if (bFiltered == true) aiRows = oSettings.aiDisplay; 
	// use all rows
	else aiRows = oSettings.aiDisplayMaster; // all row numbers

	// set up data array	
	var asResultData = new Array();
	
	for (var i=0,c=aiRows.length; i<c; i++) {
		iRow = aiRows[i];
		var aData = this.fnGetData(iRow);
		var sValue = aData[iColumn];
		
		// ignore empty values?
		if (bIgnoreEmpty == true && sValue.length == 0) continue;

		// ignore unique values?
		else if (bUnique == true && jQuery.inArray(sValue, asResultData) > -1) continue;
		
		// else push the value onto the result data array
		else asResultData.push(sValue);
	}
	
	return asResultData;
}}(jQuery));
fnGetColumnIndex()
Show details
Maintenance of web-sites can often cause unexpected headaches, particularly if the hardcoded index of an array (the columns in a DataTables instance) needs to change due to an added or removed column. This plug-in function will match a given string to the title of a column in the table and return the column index, helping to overcome this problem.
Author: Michael Ross
Code:
/*
 * Function: fnGetColumnIndex
 * Purpose:  Return an integer matching the column index of passed in string representing sTitle
 * Returns:  int:x - column index, or -1 if not found
 * Inputs:   object:oSettings - automatically added by DataTables
 *           string:sCol - required - string matching the sTitle value of a table column
 */
$.fn.dataTableExt.oApi.fnGetColumnIndex = function ( oSettings, sCol ) 
{
	var cols = oSettings.aoColumns;
	for ( var x=0, xLen=cols.length ; x<xLen ; x++ )
	{
		if ( cols[x].sTitle.toLowerCase() == sCol.toLowerCase() )
		{
			return x;
		};
	}
	return -1;
}
fnGetDisplayNodes()
Show details
Get a list of all TR nodes in the table which are available (visible) after filtering.
Author: Sara Talley
Code:
/*
 * Function: fnGetDisplayNodes
 * Purpose:  Return an array with the TR nodes used for displaying the table
 * Returns:  array node: TR elements
 *           or
 *           node (if iRow specified)
 * Inputs:   object:oSettings - automatically added by DataTables
 *           int:iRow - optional - if present then the array returned will be the node for
 *             the row with the index 'iRow'
 */
$.fn.dataTableExt.oApi.fnGetDisplayNodes = function ( oSettings, iRow )
{
	var anRows = [];
	if ( oSettings.aiDisplay.length !== 0 )
	{
		if ( typeof iRow != 'undefined' )
		{
			return oSettings.aoData[ oSettings.aiDisplay[iRow] ].nTr;
		}
		else
		{
			for ( var j=oSettings._iDisplayStart ; j<oSettings._iDisplayEnd ; j++ )
			{
				var nRow = oSettings.aoData[ oSettings.aiDisplay[j] ].nTr;
				anRows.push( nRow );
			}
		}
	}
	return anRows;
};
fnGetFilteredData()
Show details
Retrieve a data array for rows after filtering.
Author: mikej
Code:
$.fn.dataTableExt.oApi.fnGetFilteredData = function ( oSettings ) {
	var a = [];
	for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ ) {
		a.push(oSettings.aoData[ oSettings.aiDisplay[i] ]._aData);
	}
	return a;
}
fnGetFilteredNodes()
Show details
Retrieve an array with all TR nodes after filtering.
Author: Allan Jardine
Code:
$.fn.dataTableExt.oApi.fnGetFilteredNodes = function ( oSettings )
{
	var anRows = [];
	for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
	{
		var nRow = oSettings.aoData[ oSettings.aiDisplay[i] ].nTr;
		anRows.push( nRow );
	}
	return anRows;
};
fnGetHiddenNodes()
Show details
Get a list of all TR nodes in the table which are not currently visible (useful for building forms).
Author: Allan Jardine
Code:
$.fn.dataTableExt.oApi.fnGetHiddenTrNodes = function ( oSettings )
{
	/* Note the use of a DataTables 'private' function thought the 'oApi' object */
	var anNodes = this.oApi._fnGetTrNodes( oSettings );
	var anDisplay = $('tbody tr', oSettings.nTable);
	
	/* Remove nodes which are being displayed */
	for ( var i=0 ; i<anDisplay.length ; i++ )
	{
		var iIndex = jQuery.inArray( anDisplay[i], anNodes );
		if ( iIndex != -1 )
		{
			anNodes.splice( iIndex, 1 );
		}
	}
	
	/* Fire back the array to the caller */
	return anNodes;
}
fnLengthChange()
Show details
Change the number of records that can be viewed on a single page in DataTables.
Author: Pedro Alves
Code:
/*
 * Function: fnLengthChange
 * Purpose:  Change the number of records on display
 * Returns:  array:
 * Inputs:   object:oSettings - DataTables settings object
 *           int:iDisplay - New display length
 */
$.fn.dataTableExt.oApi.fnLengthChange = function ( oSettings, iDisplay )
{
	oSettings._iDisplayLength = iDisplay;
	oSettings.oApi._fnCalculateEnd( oSettings );
	
	/* If we have space to show extra rows (backing up from the end point - then do so */
	if ( oSettings._iDisplayEnd == oSettings.aiDisplay.length )
	{
		oSettings._iDisplayStart = oSettings._iDisplayEnd - oSettings._iDisplayLength;
		if ( oSettings._iDisplayStart < 0 )
		{
			oSettings._iDisplayStart = 0;
		}
	}
	
	if ( oSettings._iDisplayLength == -1 )
	{
		oSettings._iDisplayStart = 0;
	}
	
	oSettings.oApi._fnDraw( oSettings );
	
	$('select', oSettings.oFeatures.l).val( iDisplay );
}

/* Example */
$(document).ready(function() {
	var oTable = $('#example').dataTable();
	oTable.fnLengthChange( 100 );
} );
fnMultiFilter()
Show details
This plug-in adds to DataTables the ability to set multiple column filtering terms in a single call (particularly useful if using server-side processing). Used in combination with the column sName parameter, simply pass in an object with the key/value pair being the column you wish to search on, and the value you wish to search for.
Author: mrkevans
Code:
$.fn.dataTableExt.oApi.fnMultiFilter = function( oSettings, oData ) {
	for ( var key in oData )
	{
		if ( oData.hasOwnProperty(key) )
		{
			for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
			{
				if( oSettings.aoColumns[i].sName == key )
				{
					/* Add single column filter */
					oSettings.aoPreSearchCols[ i ].sSearch = oData[key];
					break;
				}
			}
		}
	}
	this.oApi._fnDraw( oSettings );
}

/* Example call */
$(document).ready(function() {
	var oTable = $('#example').dataTable( {
		"aoColumns": [
			{ "sName": "engine" },
			{ "sName": "browser" },
			{ "sName": "platform" },
			{ "sName": "version" },
			{ "sName": "grade" }
		]
	} );
	oTable.fnMultiFilter( { "engine": "Gecko", "browser": "Cam" } );
} );
fnReloadAjax()
Show details
By default DataTables only uses the sAjaxSource variable at initialisation time, however it can be useful to re-read an Ajax source and have the table update. Typically you would need to use the fnClearTable() and fnAddData() functions, however this wraps it all up in a single function call. Note: To reload data when using server-side processing, just use the built-in API function fnDraw rather than this plug-in.
Author: Allan Jardine
Code:
$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback )
{
	if ( typeof sNewSource != 'undefined' )
	{
		oSettings.sAjaxSource = sNewSource;
	}
	this.oApi._fnProcessingDisplay( oSettings, true );
	var that = this;
	
	oSettings.fnServerData( oSettings.sAjaxSource, null, function(json) {
		/* Clear the old information from the table */
		that.oApi._fnClearTable( oSettings );
		
		/* Got the data - add it to the table */
		for ( var i=0 ; i<json.aaData.length ; i++ )
		{
			that.oApi._fnAddData( oSettings, json.aaData[i] );
		}
		
		oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
		that.fnDraw( that );
		that.oApi._fnProcessingDisplay( oSettings, false );
		
		/* Callback user function - for event handlers etc */
		if ( typeof fnCallback == 'function' )
		{
			fnCallback( oSettings );
		}
	} );
}

/* Example call to load a new file */
oTable.fnReloadAjax( 'media/examples_support/json_source2.txt' );

/* Example call to reload from original file */
oTable.fnReloadAjax();
fnSetFilteringDelay()
Show details
Enables filtration delay for keeping the browser more responsive while searching for a longer keyword.
Author: Zygimantas Berziunas, Allan Jardine and vex
Code:
jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay = function ( oSettings, iDelay ) {
	/*
	 * Type:        Plugin for DataTables (www.datatables.net) JQuery plugin.
	 * Name:        dataTableExt.oApi.fnSetFilteringDelay
	 * Version:     2.2.0
	 * Description: Enables filtration delay for keeping the browser more
	 *              responsive while searching for a longer keyword.
	 * Inputs:      object:oSettings - dataTables settings object
	 *              integer:iDelay - delay in miliseconds
	 * Returns:     JQuery
	 * Usage:       $('#example').dataTable().fnSetFilteringDelay(250);
	 * Requires:	  DataTables 1.6.0+
	 *
	 * Author:      Zygimantas Berziunas (www.zygimantas.com) and Allan Jardine (v2)
	 * Created:     7/3/2009
	 * Language:    Javascript
	 * License:     GPL v2 or BSD 3 point style
	 * Contact:     zygimantas.berziunas /AT\ hotmail.com
	 */
	var _that = this;
	this.each( function ( i ) {
		$.fn.dataTableExt.iApiIndex = i;
		var	iDelay = (iDelay && (/^[0-9]+$/.test(iDelay)) ? iDelay : 250),
			$this = this, 
			oTimerId = null, 
			sPreviousSearch = null,
			anControl = $( 'input', _that.fnSettings().aanFeatures.f );
		
			anControl.unbind( 'keyup' ).bind( 'keyup', function() {
			var $$this = $this;

			if (sPreviousSearch === null || sPreviousSearch != anControl.val()) {
				window.clearTimeout(oTimerId);
				sPreviousSearch = anControl.val();	
				oTimerId = window.setTimeout(function() {
					$.fn.dataTableExt.iApiIndex = i;
					_that.fnFilter( anControl.val() );
				}, iDelay);
			}
		});
		
		return this;
	} );
	return this;
}

/* Example call */
$(document).ready(function() {
	$('.dataTable').dataTable().fnSetFilteringDelay();
} );
fnStandingRedraw()
Show details
Redraw the table (i.e. fnDraw) to take account of sorting and filtering, but retain the current pagination settings.
Author: Jonathan Hoguet
Code:
$.fn.dataTableExt.oApi.fnStandingRedraw = function(oSettings) {
	//redraw to account for filtering and sorting
	// concept here is that (for client side) there is a row got inserted at the end (for an add) 
	// or when a record was modified it could be in the middle of the table
	// that is probably not supposed to be there - due to filtering / sorting
	// so we need to re process filtering and sorting
	// BUT - if it is server side - then this should be handled by the server - so skip this step
	if(oSettings.oFeatures.bServerSide === false){
		var before = oSettings._iDisplayStart;
		oSettings.oApi._fnReDraw(oSettings);
		//iDisplayStart has been reset to zero - so lets change it back
		oSettings._iDisplayStart = before;
		oSettings.oApi._fnCalculateEnd(oSettings);
	}
	
	//draw the 'current' page
	oSettings.oApi._fnDraw(oSettings);
};

/* Example call */
$(document).ready(function() {
	var oTable = $('.dataTable').dataTable()
	oTable.fnStandingRedraw();
} );

Note that all contributed code is copyright to the original author, unless otherwise stated.