New in DataTables 2

DataTables 2 is a major update to DataTables and brings a wide variety of enhancements to the library. This document contains details of most of the more significant new features.

It is part of a number of related documents detailing the release of DataTables 2:

Layout and features

This is probably the one that most people working with DataTable will encounter. Positioning control elements around the table is very important to tailor the UI to your specific requirements. Previously the dom option was used in DataTables, which worked, but it was a maintenance nightmare, particularly when working with styling integrations such as Bootstrap.

As such, DataTables 2 introduces a new layout option to make working with the positioning of table elements much easier. It provides a positional grid which you can insert elements into with a simple object key made up of top or bottom, optionally followed by Start or End. A number can be placed between the two to allow multi-row operation. See layout for a visual representation of this.

The upshot of this is that we can now insert elements with a simple object key - e.g.:

new DataTable('#myTable', {
    layout: {
        topStart: 'buttons'
    }
});

Moreover, this leads to "features" in DataTables. Each control element is a "feature" that is registered with DataTables and can be configured individually in the layout object, rather than relying on the top level configuration object. DataTables has four built in features: info, pageLength, paging, and search. Extensions can add features such as buttons and searchBuilder.

Consider the case where you might need to add multiple button groups around the table. This is now trivial with DataTables 2:

new DataTable('#myTable', {
    layout: {
        topStart: {
            buttons: [ 'create', 'edit', 'remove' ]
        },
        topEnd: {
            buttons: [ 'excel', 'csv' ]
        }
    }
});

It is easy to create new features to use with layout through the DataTable.feature.register() method. You'll see more on this in future blog posts as I create additional plugins for DataTables!

Search

Search is a fundamental cornerstone to make data accessible, and that after all is what DataTables is all about. Very often when creating search components for DataTables you will want to combine multiple custom filters, while still providing the end user the ability to type their own search term. This is now a lot easier in DataTables with the new fixed search methods:

With these methods you create a "named search" which will be applied along with any other search terms, until either replaced or removed.

More than this, the search abilities of the DataTables API have been greatly increased by being able to pass in a search function, regex or a "smart" search string. The smart search of DataTables has been enhanced to support negative searching as well as more options through the new DataTables.SearchOptions object, which gives options such as exact, boundary and more.

Additionally, the built-in search is now diacritic neutral. I.e. your data can contain accented characters, and your end user type an unaccented character and it will match.

For more information about search in DataTables, please see the new manual page for Search.

Language for entries

Each DataTable shows data of a specific type. The default language string refers to the data items as "entries", but it can help your end user to understand the data on the page you you tailor the language strings to match what is being shown - e.g. for the paging information if you are showing a list of people you might want to use Showing x to y of z people. In DataTables 1 it was possible to do, but you had to tweak every language string that referenced the generic "entries" term.

DataTables 2 introduces a new language.entries option which is used by the default language strings to easily customise how the data is named. For example, the following will customise the info and pageLength strings (note also that it supports the pluralisation of i18n() to further make your table feel more natural and correct to your end users):

new DataTable('#myTable', {
    language: {
        entries: {
            _: 'people',
            1: 'person'
        }
    }
});

Captions

The caption tag is used to provide a title for a table and is now a first class citizen in DataTables, with the ability to set a caption at start up with caption and to be updated during run time with caption() and caption.node().

Data types

Operations on the data in a table depend heavily on the format and structure of the data to be displayed - for example dates are handled differently from numbers, which are handled differently from strings, etc. DataTables has always had the ability to add extra data types to it, but the APIs to do so have been fragmented. DataTables 2 brings harmonisation to data type control through its new DataTable.type() and DataTable.types() methods.

Furthermore the data type handling system in DataTables also now has the ability to automatically define classes and renders for detected data types. This is used for the built in data types for dates and numbers to provide more natural data alignment.

There is a new section in manual which goes into more depth for how to control the built in data types, and also how to register your own custom data types. For example, the following code will detect columns with IPv4 formatted data, apply correct ordering and also add a class to the columns:

DataTable.type('ipv4', {
    detect: function (data) {
        return typeof data === 'string' &&
            data.match(/^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/)
                ? 'ipv4'
                : null;
    },
    order: {
        pre: function (data) {
            return Number(
                data
                    .split('.')
                    .map((num, idx) => num * Math.pow(2, (3 - idx) * 8))
                    .reduce((a, v) => ((a += v), a), 0)
            );
        }
    },
    className: 'dt-data-ipv4'
});

Ready actions

A common support question that crops up in the forums is why interaction with the API doesn't work when using ajax. The answer is simply that Ajax loaded data is async, so your code needs to wait for the data to be loaded from the server before it can be used. initComplete can be used to address this and when you know the answer, this is straightforward, but if you are new to async programming it can be frustrating.

To help address this, and to allow code reuse between async and sync loaded tables, DataTables 2 introduces the new ready() method. This function takes a single argument and will execute the given function when the table has its data ready (possibly immediately if the data is ready).

Consider:

let table = new DataTable('#myTable');
 
table.ready(function () {
    // Actions to take when the table is ready
    // ...
});

and:

let table = new DataTable('#myTable', {
    ajax: '/api/data'
});
 
table.ready(function () {
    // Actions to take when the table is ready
    // ...
});

The program structure is identical, but the ready callback function will only be executed when the table has its data fully loaded.

Server-side processing JSON properties

DataTables has long had the ability to specify the property name for where it should look for the array of data in a JSON object to be shown in the table through the ajax.dataSrc option. However, that hasn't extended to server-side processing where you would often have to write your own Ajax call if the returned parameter names don't match what DataTables expects.

With v2, ajax.dataSrc has been extended so that it can be given as an object with the ability to provide a mapping for each of the expected parameters individually. For example the following mapping could be used:

new DataTable('#myTable', {
    ajax: {
        url: '/api/users',
        dataSrc: {
            data: 'results',
            draw: 'request',
            recordsTotal: 'total',
            recordsFiltered: 'filtered'
        }
    },
    serverSide: true
});

Column methods

DataTables 2 expands the columns API with a number of new methods:

Utility methods

DataTables already provided a number of its internal methods through the API such as DataTable.util.get() and DataTable.util.set(). These methods have now been extended in DataTables 2 with the following methods added:

  • DataTable.util.stripHtml() - Remove HTML. Also provides the ability to give your own parser should you need more accuracy than the built in regex.
  • DataTable.util.escapeHtml() - Escape HTML characters in a string to make them safe to inject into the document.
  • DataTable.util.unique() - Get the unique items from a provided array.
  • DataTable.util.diacritics() - Remove accents from a string. Also provides the ability to modify how diacritics are removed from strings if the built in method is not sufficient for your needs.

These methods aren't the core functionality of DataTables, it isn't a utility library like Lodash, but DataTables uses these methods internally and they are often useful for plug-ins and extensions to help encourage code reuse.

And more

Those are just the highlights. There are plenty more new features in DataTables 2, such as improved support for complex headers / footers, ordering specification with tuples, additional CSS variables and more. The release notes has details of all additions and changes.