Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 56 ยท Plugins and Utilities

DataTables with jQuery

Turn HTML tables into sortable, searchable, paged grids with the DataTables plugin: array and AJAX data, column search, events, the API, child rows and several tables.

A plain HTML table is fine for ten rows. At a few hundred rows users want to sort, search and page through the data. DataTables is the best-known jQuery plugin for exactly that. You give it a table (or a data source) and it adds a search box, sortable column headers, a page-length menu, paging and an information line, and it keeps working at tens of thousands of rows because it renders only the visible page.

This lesson covers the version 2 line of DataTables, which still uses jQuery. You will initialise it from markup and from arrays, load data through AJAX, search per column, react to events, use the API, show child rows and run several tables on one page. If you have not used plugins before, read Using Plugins and jQuery UI first.

What DataTables adds

Search Global and per-column filters.
Sort Click a header, shift-click for more.
Paging Only the visible page is drawn.
Data sources HTML, arrays, AJAX, server-side.
1 / 2

Loading it

DataTables ships as a core file plus a styling package. With a CDN you load jQuery, the core, the styling script and the matching stylesheet:

HTML
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/dataTables.dataTables.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/js/dataTables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/js/dataTables.dataTables.min.js"></script>

There are matching packages for Bootstrap, Foundation and others (datatables.net-bs5, and so on). Pick the one that fits your site's CSS. In version 2 $.fn.dataTable is the same as $.fn.DataTable, but only .DataTable() (capital D, T) returns the new API object, so prefer it.

From existing HTML

The simplest start is a normal table with a <thead> and a <tbody>:

JavaScript
$("#people").DataTable();

That one call enables search, ordering and paging. Options go in an object: pageLength, lengthMenu, order (an array such as [[2, "desc"]]), searching, paging, info, ordering, scrollY, language (translate the interface) and layout (where the controls go).

From a JavaScript array

When you already have data in JavaScript, pass it in and describe the columns. The <table> can be empty:

DataTables from an array

Look at the columns option: data names the property, title becomes the header and render formats the displayed value while sorting still uses the raw number. render can also take an object such as { display: ..., sort: ..., filter: ... } when the three need different values, which is how dates and currencies sort correctly.

Loading data with AJAX

Set the ajax option and DataTables fetches the data for you. The default expects { "data": [ ... ] }; use dataSrc to point at another property, or "" if the response is a plain array:

JavaScript
$("#users").DataTable({
  ajax: { url: "/api/users", dataSrc: "" },
  columns: [{ data: "id" }, { data: "name" }, { data: "email" }]
});

With ajax: "/api/users.json" the plugin sends a GET request. For custom behaviour, ajax can also be a function (requestData, callback, settings); call callback({ data: rows }) when you are ready. That is useful for authentication headers, caching and tests, and it is what the next example uses so it works without a server.

AJAX-style loading with a function and reload

For very large data sets, switch to server-side processing (serverSide: true). Then DataTables sends draw, start, length, search[value] and order[0][column] on each page, sort or search, and your server replies with recordsTotal, recordsFiltered and data. Use it when you cannot send all rows to the browser. Always validate and limit those parameters on the server.

Searching: global and per column

The search box filters on all columns. You can also drive it from code: table.search("ada").draw(). A common pattern is one input per column:

JavaScript
table.columns().every(function () {
  var column = this;
  $("input", column.footer()).on("input", function () {
    if (column.search() !== this.value) {
      column.search(this.value).draw();
    }
  });
});

Two details trip people up. Search and order calls only change the settings; you must call .draw() to repaint. And a search is a smart search by default (words in any order); pass search(value, { regex: true, smart: false }) for regular expressions. You can also add custom filters with $.fn.dataTable.ext.search.push(function (settings, data) { ... return true/false; }), for example a numeric range.

Events

Bind to the table element (.on() on either the jQuery object or the API object), and add the .dt namespace if you use the jQuery form:

Event Fires when
init.dt initialisation is complete
draw.dt the table is redrawn
order.dt, search.dt, page.dt, length.dt the user changes sort, filter, page or length
xhr.dt an Ajax load finished
preXhr.dt just before the request
click on tbody tr your own row events

Rows are created and destroyed as the user pages, so attach row handlers by delegation from the table, exactly as in Event Delegation:

JavaScript
$("#people tbody").on("click", "tr", function () {
  var row = table.row(this).data();
  console.log(row.name);
});

The API

$("#t").DataTable() returns the API. It is chainable and works on groups: table.rows(), table.columns(), table.cells() each return a collection; row(selector), column(selector) and cell(selector) return one item. Typical calls:

  • table.row.add({ ... }).draw() and table.row(this).remove().draw()
  • table.rows().data().toArray(), table.column(1).data().unique()
  • table.page("next").draw("page"), table.order([1, "desc"]).draw()
  • table.clear().rows.add(newData).draw() to replace everything
  • table.destroy() before re-initialising the same table (initialising twice shows a warning)

Child rows

A child row is an extra row that opens beneath a data row, a good place for details that do not fit in a column:

Child rows and two tables on one page

Notice $("<div>").text(...).html(): the note comes from data, so it is escaped before being inserted as HTML. child() takes an HTML string, so untrusted text must be escaped like any other content you insert. The same applies to render functions that return markup.

Each DataTable() call is independent: the second table has its own search box, paging and API object. Keep the returned objects in variables rather than calling $.fn.dataTable.tables() unless you really need to discover them.

Practical advice

  • Give columns width or set autoWidth: false, and put style="width:100%" on the table, so the layout stays steady.
  • For tables inside hidden tabs or modals, call table.columns.adjust() after they become visible.
  • Use deferRender: true for large arrays and scrollY with scrollCollapse for fixed-height grids.
  • Ship only the extensions you use (Buttons, Responsive, FixedHeader, Select). They are separate packages.
  • Check accessibility: sortable headers need to be reachable by keyboard, and DataTables provides this by default.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You changed a search with column.search("ada") but the table did not update. What is missing?

    search(), order() and similar calls only change the settings. draw() repaints the table.
  2. 2. How should you attach click handlers to rows in a DataTable that has several pages?

    DataTables draws only the visible rows, so direct handlers would vanish when the page changes. Delegation survives redraws.
  3. 3. What does the render function in a column definition do?

    render formats the cell. Using the object form {display, sort, filter} lets the display differ from the sort value.
  4. 4. When should you use serverSide: true?

    Server-side processing sends draw, start, length, search and order to your server, which returns just the needed slice.
  5. 5. What must you do before initialising DataTables again on a table that is already a DataTable?

    A second initialisation raises a warning and is ignored. destroy() restores the original table.

Summary

  • DataTables adds search, sorting, paging and a rich API to HTML tables; load jQuery, the core, a styling package and its CSS.
  • Initialise from markup, from a data array with columns, or from ajax (URL or function); use serverSide for huge data.
  • Searching and ordering need .draw(); per-column search uses column.search(...).
  • Delegate row events, escape any HTML you pass to child() or render, and destroy() before re-initialising.
  • Several tables on one page are independent, each with its own API object.

Next: a quick tour of other popular plugins in Using Plugins and jQuery UI, or move on to What Changed in jQuery 3.