As I mentioned earlier today in a previous post, I have been working on an open data project with a few individuals who reside all across Canada. That being said, as one of the developers and requirements were to use the jQuery DataTable plugin. However, the problem that existed was that we required to have more then one ‘data table’ on a single page, which resulted in a major pain in the royal rump (not saying my rump is royal or anything, just a phrase!).

So… after doing some digging, I found a possible solution. The solution in which I had found, was one in which many of individuals have been searching for and trying to implement with ease. However, the solution could introduce some errors and problems if not used intelligently and with a lot of awareness.

That being said, here is the solution that I had found. The jQuery DataTable plugin, allows multiple instances of the data tables to be created with a single selector and a single object of settings. When trying to interact with an individual data table, it becomes various difficult. This is because the jQuery DataTable plugin, once initialized, uses the first instance of the data table as the primary active one. Trying to perform operations like call API functions for another instance of the table – one is presented with errors unless the current Api index is manually changed to the table’s index in which you want to interact with.

An example of what I mean is as follows:

$(document).ready(function() {
	$('.datatable').dataTable();

	// add data to the first table
	$('.datatable').dataTable().fnAddData([ … ]);

	// now I want to add data to the second table. But how do I do this? …
	// well, change the Api index value to 1.
	$.fn.dataTableExt.iApiIndex = 1;

	// Yay! Now I can add data to the second table …
	$('.datatable').dataTable().fnAddData([ … ]);
});

Now, who in their right mind wants to manage the jQuery DataTable’s iApiIndex value throughout their entire script? I know that I sure do not. Therefore, I have created a very simple solution to help manage just this.

/**
 * File:				dataTableManager.js
 * Version:				0.0.1
 * Description:			Assists in managing one or more jQuery Data Tables at once.
 * Author:				Aaron McGowan ( www.amcgowan.ca )
 * Created:				04/11/2010
 * Language:			JavaScript
 * Contact:				me@amcgowan.ca
 */

/** Test if jQuery and jQuery's dataTable plugin exists - if not, alert
	the user. Note: They must exist for DataTableManager to operate correctly and
	also appear at run time */
if( !jQuery || !jQuery.fn.dataTableExt ) {
	alert("This class requires jQuery and jQuery's dataTable plugin");
} else {

/**
 * DataTableManager
 *
 * Constructor for data table manager class.
 *
 * @access: public
 * @param:  string			Contains the string selector for selecting the jQuery Data table elements.
 * @param:	object			Contains an object of settings which will be used to initialize the jQuery Data Table.
 * @param: 	array			Contains an array of names used to identify data tables on a page. Names appear in order of tables.
 * @return: void
 */
var DataTableManager = function(dataTableSelector, settings, names) {
	this._init(dataTableSelector, settings, names);
};

/**
* DataTableManager.prototype
*
* Define member variables/properties and methods/functions for
* an the DataTableManager class instance.
*/
DataTableManager.prototype = {
	/**
	* _tableInstanceIndexes
	*
	* An array of indexes, numeric values starting from 0 to n, in which n is one less then
	* the number of data table instances.
	*/
	_tableInstanceIndexes : [],

	/**
	* _tableInstanceNames
	*
	* An object of which each property is an identifying name for a table
	* with the numeric value of which index it is associated with in _tableInstanceIndexes.
	*/
	_tableInstanceNames : {},

	/**
	* _dataTableSelector
	*
	* The selector string in which was used to initialize the data tables.
	*/
	_dataTableSelector : null,

	/**
	* GetCurrentTableIndex
	*
	* @access: public
	* @param:  void
	* @return: int
	*/
	GetCurrentTableIndex : function() {
		return jQuery.fn.dataTableExt.iApiIndex;
	},

	/**
	* GetDataTable
	*
	* @access: public
	* @param:  mixed		Contains the identifier for a table to set active, and return an instance of.
	*						This can either be the string (name) representation and or the numeric index.
	* @return: mixed		Returns null on failure, else returns the data table instance.
	*/
	GetDataTable : function(key) {
		/* If key is undefined and or null, return the current data table instance */
		if( undefined == key || null == key ) {
			return jQuery(this._dataTableSelector).dataTable();
		}

		/* Test if the key is being used as the string represetation */
		if( undefined != this._tableInstanceNames[key] && undefined != this._tableInstanceIndexes[this._tableInstanceNames[key]] ) {
			jQuery.fn.dataTableExt.iApiIndex = this._tableInstanceIndexes[this._tableInstanceNames[key]];
		}
		/* Test if the key is simply the numeric index */
		else if( undefined != this._tableInstanceIndexes[key] ) {
			jQuery.fn.dataTableExt.iApiIndex = this._tableInstanceIndexes[key];
		}
		else {
			return null;
		}

		return jQuery(this._dataTableSelector).dataTable();
	},

	/**
	* _init
	*
	* Initializing method.
	*
	* @access: private
	* @param:  string			Contains the string selector for selecting the jQuery Data table elements.
	* @param:	object			Contains an object of settings which will be used to initialize the jQuery Data Table.
	* @param: 	array			Contains an array of names used to identify data tables on a page. Names appear in order of tables.
	* @return: void
	*/
	_init : function(dataTableSelector, settings, names) {
		/* set the selector */
		this._dataTableSelector = dataTableSelector;

		/* initialize the data table */
		var dTable = jQuery(dataTableSelector).dataTable(settings);

		/* build the instance indexes array, and assign name associations if necessary */
		for( var i = 0; i < dTable.length; ++i ) {
			this._tableInstanceIndexes[i] = i;
			if( names[i] ) {
				this._tableInstanceNames[names[i]] = i;
			}
		}
	}
}; /* end DataTableManager.prototype */

} /* end 'else' in if( !jQuery || !jQuery.fn.dataTableExt ) { */

This script is free for you to download, use and share. Please just simply provide attribution (credit) to me if you plan on re-distributing it.

An example in which this script can be used is:

$(document).ready(function() {
	var dtManager = new DataTableManager('.datatable', {}, ['first_table', 'second_table']);

	// Add data to the first table
	dtManager.GetDataTable('first_table').fnAddData([ … ]);

	// Add data to the second table
	dtManager.GetDataTable('second_table').fnAddData([ … ]);
});

As you can see, instead of managing the iApiIndex value yourself and trying to remember the numeric value for each data table, you can now simply identify the tables with a string representation and simply interact with the data table manager which manages the iApiIndex value for you.

Note: This script is dependent upon jQuery and DataTables plugin for jQuery.

Enjoy and happy coding!