DataTables logo DataTables

ads by Yoggrt

Type detection

When a DataTable is initialised, each column is scanned automatically for the type of data it contains, which in turn allows DataTables to apply the require type of sorting function. There are three built-in types (string, date and numeric) but this can readily be expanded using the functions below. This can make installed a sorting plug-in much easier since you need not specify the sType for the column - it will be picked up automatically.

How to use DataTables plug-in type detection functions

To use of one of the plug-in type detections functions below, you simply need to include it and its counterpart sorting function, in the Javascript available for your page, after you load the DataTables library, but before you initialise the DataTable. Then all you need to do is initialise the DataTable and the type will be automatically detected. As an example the code below makes use of the numeric comma type detection and sorting functions, saved into two different files for clarity (live example):

<script type="text/javascript" src="jquery.dataTables.js"></script>
<script type="text/javascript" src="dataTables.numericCommaSort.js"></script>
<script type="text/javascript" src="dataTables.numericCommaTypeDetect.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$('#example').dataTable();
	} );
</script>

Plug-in type detection functions

Commas for decimal place
Show details
Automatically detect numbers which use a comma in the place of a decimal point to allow them to be sorted numerically.
Author: Allan Jardine
Code:
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';
	}
);
Currency
Show details
This plug-in will add automatic detection for currency columns to DataTables. Note that only $ and £ symbols are detected with this code, but it is trivial to add more or change the current ones. This is best used in conjunction with the currency sorting plug-in.
Author: Allan Jardine
Code:
jQuery.fn.dataTableExt.aTypes.unshift(  
    function ( sData )  
    {  
        var sValidChars = "0123456789.-,";  
        var Char;  
          
        /* Check the numeric part */  
        for ( i=1 ; i<sData.length ; i++ )   
        {   
            Char = sData.charAt(i);   
            if (sValidChars.indexOf(Char) == -1)   
            {  
                return null;  
            }  
        }  
          
        /* Check prefixed by currency */  
        if ( sData.charAt(0) == '$' || sData.charAt(0) == '£' )  
        {  
            return 'currency';  
        }  
        return null;  
    }  
);
File size
Show details
Detect "file size" type columns automatically. Commonly used for computer file sizes, this can allow sorting to take the order of magnitude indicated by the label (GB etc) into account.
Author: anjibman
Code:
jQuery.fn.dataTableExt.aTypes.unshift(
    function ( sData )
    {
        var sValidChars = "0123456789";
        var Char;

        /* Check the numeric part */
        for ( i=0 ; i<(sData.length - 3) ; i++ )
        {
            Char = sData.charAt(i);
            if (sValidChars.indexOf(Char) == -1)
            {
                return null;
            }
        }

        /* Check for size unit KB, MB or GB */
        if ( sData.substring(sData.length - 2, sData.length) == "KB"
            || sData.substring(sData.length - 2, sData.length) == "MB"
            || sData.substring(sData.length - 2, sData.length) == "GB" )
        {
            return 'file-size';
        }
        return null;
    }
);
Formatted numbers
Show details
This plug-in will strip out non-numeric formatting characters such that a formatted number (for example 1,000,000) can be detected automatically and sorted numerically. Note that characters a-z are not automatically removed, otherwise there is a risk of detecting columns as numeric which should not be. Also note that the jQuery 1.7 method isNumeric is used, so jQuery 1.7 is required.
Author: Allan Jardine
Code:
jQuery.fn.dataTableExt.aTypes.unshift(  
    function ( sData )  
    {  
		var deformatted = sData.replace(/[^\d\-\.\/a-zA-Z]/g,'');
		if ( $.isNumeric( deformatted ) ) {
			return 'formatted-num';
		}
        return null;  
    }  
);
HTML auto detection
Show details
It can be very useful to have DataTables default to it's built in type of HTML, rather than string, which a column does not fit the requirements of any other type. The way this method works is to put the 'html' type at the end of aTypes, which means it will be set as that type only if none of the other types match the data in question.
Author: Allan Jardine
Code:
jQuery.fn.dataTableExt.aTypes.unshift(
	function ( sData ) {
		return 'html';
	}
);
IP address detection
Show details
Automatically detect IP addresses in dot notation. Goes perfectly with the IP address sorting function.
Author: Brad Wasson
Code:
jQuery.fn.dataTableExt.aTypes.unshift(
	function ( sData )
	{
		if (/^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/.test(sData)) {
			return 'ip-address';
		}
		return null;
	}
);
Numbers with HTML
Show details
This type-detection plug-in will look at an HTML string from a data cell, strip the HTML tags and then check to see if the remaining data is numeric. If it is, then the data can be sorted numerically with the Numbers with HTML sorting plug-in.
Author: Allan Jardine
Code:
jQuery.fn.dataTableExt.aTypes.unshift( function ( sData )
{
	sData = typeof sData.replace == 'function' ?
		sData.replace( /<.*?>/g, "" ) : sData;
	sData = $.trim(sData);
	
	var sValidFirstChars = "0123456789-";
	var sValidChars = "0123456789.";
	var Char;
	var bDecimal = false;
	
	/* Check for a valid first char (no period and allow negatives) */
	Char = sData.charAt(0); 
	if (sValidFirstChars.indexOf(Char) == -1) 
	{
		return null;
	}
	
	/* Check all the other characters are valid */
	for ( var i=1 ; 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 'num-html';
} );
UK date type detection
Show details
Automatically detect British (dd/mm/yyyy) date types. Goes with the UK date sorting function pair.
Author: Andy McMaster
Code:
jQuery.fn.dataTableExt.aTypes.unshift(
	function ( sData )
	{
		if (sData !== null && sData.match(/^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/(19|20|21)\d\d$/))
		{
			return 'uk_date';
		}
		return null;
	} 
);
Week day detection
Show details
Automatically detect week days (English) and sort them chronologically rather than alphabetically. Goes with the week day sorting function pair.
Author: Pål Oliver Kristiansen
Code:
jQuery.fn.dataTableExt.aTypes.unshift(
  function ( sData ){
    var sValidStrings = 'monday,tuesday,wednesday,thursday,friday,saturday,sunday';
		
    if (sValidStrings.indexOf(sData.toLowerCase()) >= 0){
      return 'weekdays-sort';
    }
		
    return null;						
  }
);

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