DataTables sorting and type detection example

Preamble

When dealing with your own data formatting, it can often be very useful to have DataTables detect data types and sorting them accordingly for types which are not build into DataTables. For this reason plug-in support is provided to allow custom type detection and sorting.

This example shows sorting with a comma (',') for a decimal place. These plug-ins (and others can be found on DataTables.net.

Live example

Show entries
Search:
Rendering engine Browser Platform(s) Engine version CSS grade
Rendering engine Browser Platform(s) Engine version CSS grade
Gecko Firefox 1.0 Win 98+ / OSX.2+ 1,7 A
Gecko Firefox 1.5 Win 98+ / OSX.2+ 1,8 A
Gecko Firefox 2.0 Win 98+ / OSX.2+ 1,8 A
Gecko Firefox 3.0 Win 2k+ / OSX.3+ 1,9 A
Gecko Camino 1.0 OSX.2+ 1,8 A
Gecko Camino 1.5 OSX.3+ 1,8 A
Gecko Netscape 7.2 Win 95+ / Mac OS 8.6-9.2 1,7 A
Gecko Netscape Browser 8 Win 98SE+ 1,7 A
Gecko Netscape Navigator 9 Win 98+ / OSX.2+ 1,8 A
Gecko Mozilla 1.0 Win 95+ / OSX.1+ 1 A
Showing 1 to 10 of 57 entries

Initialisation code

/* Note 'unshift' does not work in IE6. A simply array concatenation would. This is used
 * to give the custom type top priority
 */
jQuery.fn.dataTableExt.aTypes.unshift(
	function ( sData )
	{
		var sValidChars = "0123456789-,";
		var Char;
		var bDecimal = false;
		
		/* Check the numeric part */
		for ( i=0 ; i<sData.length ; i++ )
		{
			Char = sData.charAt(i);
			if (sValidChars.indexOf(Char) == -1)
			{
				return null;
			}
			
			/* Only allowed one decimal place... */
			if ( Char == "," )
			{
				if ( bDecimal )
				{
					return null;
				}
				bDecimal = true;
			}
		}
		
		return 'numeric-comma';
	}
);

jQuery.fn.dataTableExt.oSort['numeric-comma-asc']  = 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));
};

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

Other examples

Basic initialisation

Advanced initialisation

Data sources

Server-side processing

API

Plug-ins

Please refer to the DataTables documentation for full information about it's API properties and methods.