Saturday 27th August, 2011

Getting started with DataTables

Update: The DataTables manual now has an installing section which details how to get up and running with DataTables quickly and easily. This blog post was written prior to the release of DataTables 1.10 and therefore is outdated in areas, but is left for historic reference.

DataTables is a powerful Javascript library for adding interaction features to HTML tables, and while simplicity is a core design principle for the project as a whole, it can be quite daunting to get started. In this article I'll introduce the basic concepts that you will need to know to get going with DataTables, and you will find that in a very short space of time you'll be able to create advanced table controls, tuned to your specific requirements.

Dependencies

DataTables has only one dependency (other software upon which it relies in order to work) - jQuery. Being a jQuery plug-in, DataTables makes use of many of the excellent features that jQuery provides, and hooks into the jQuery plug-in system, in the same way that all other jQuery plug-ins work. jQuery 1.3 or newer will work with DataTables, although typically you will want to use the latest version (1.6.2 at the time of writing). DataTables includes everything else that it requires to operate.

HTML requirements

All DataTables needs in your HTML is a

which is well formed (i.e. valid HTML), with a header (defined by a HTML tag) and a body (a tag). A typical table might look like this:

<table id="table_id">
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Row 1 Data 1</td>
            <td>Row 1 Data 2</td>
        </tr>
        <tr>
            <td>Row 2 Data 1</td>
            <td>Row 2 Data 2</td>
        </tr>
    </tbody>
</table>

If you are generating your HTML document using a server-side program, such as a PHP script, a Ruby script, a C# program or anything else - all they need to do is output your table like this. This is exactly what you would have for a normal HTML table, although sometimes you might need to add the

and tags, as these aren't always used (they allow DataTables to know what should be used for the column headers and the click-to-sort controls).

Including the Javascript and CSS

The first thing to do when you want to use DataTables, is to download the latest version from the DataTables download page. Unzip the downloaded file and upload it to your web-server.

To be able to use DataTables on your page, you must first include the library in your web-page; this is done using the