Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 56 ยท Projects

Project: Live Search and Sortable Table

Build a data table that loads rows from a stand-in AJAX call, filters as you type with match highlighting, sorts by column with .sort() and shows an empty state.

Data tables are the workhorse of admin screens, dashboards and reports, and users expect two things from them immediately: a search box that narrows the rows as they type, and headers they can click to sort. Both are perfect jQuery exercises because they combine nearly everything from the course: AJAX, creating elements, events, filtering and data storage.

In this project you will build the table in two stages. First you load rows from a stand-in server, render them safely and add a live search with highlighted matches and an empty state. Then you add sortable columns using the native Array.prototype.sort() and keep the screen reader informed with aria-sort.

The plan

Load A stand-in AJAX call returns the rows.
Render Build each row with .text(), never raw HTML.
Filter Hide rows that do not match what was typed.
Sort Reorder the existing rows by a column.
1 / 2

The stand-in server

The page you are reading cannot call a real API, and a project should not depend on one anyway while you build the interface. So we write a function that behaves like an AJAX call: it returns a promise and resolves it a moment later with data. The rest of the code uses .done() on it exactly as it would on the object that $.getJSON() returns. When a real endpoint exists, you replace this one function and nothing else changes.

JavaScript
function fetchMountains() {
  var deferred = $.Deferred();
  setTimeout(function () {
    deferred.resolve(MOUNTAINS);
  }, 400);
  return deferred.promise();
}

$.Deferred() creates a promise you control, and .promise() hands out the read-only half so callers cannot resolve it by accident. The delay lets you see the loading state, which is part of the job: a table that stays blank for a second makes users think it is broken.

Rendering rows safely

Every row is built with $("<tr>") and .text(), never by pasting strings into .html(). Data from a server may contain < or &, and .text() guarantees it is shown literally. The best practices lesson calls this the number one habit for avoiding XSS.

While rendering, each cell stores its raw value with .data("value", ...). Later, the filter reads the text from there and the sorter compares the numbers from there, so neither has to parse text back out of the DOM.

Live search with highlighting

The search box listens for the input event, which fires on every change including paste and the clear button. Filtering on each keystroke is cheap for hundreds of rows, but we still debounce by 120 ms so a fast typist triggers one pass instead of ten.

For each row we decide whether it matches, then toggle the hidden property. Matching is a case-insensitive substring test against all the cells of the row. Highlighting is the more delicate part. The tempting approach is to replace the query with <mark>query</mark> inside an HTML string, but that breaks when the text contains characters like & and opens the door to injection. The safe way is to split the text into pieces around the match and append each piece as either a text node or a <mark> element created with .text().

String.prototype.split() with a capturing group keeps the separators in the result, so the odd-numbered items are always the matches. Because the query is user input, special characters such as . or ( must be escaped before they become part of a regular expression.

Live search with highlighting and an empty state

Some points about this code:

  • $.map() flattens whatever the callback returns, and returning a jQuery object is fine: the result is an array of the row objects, which .append() accepts. All rows are inserted in one call, so the browser lays the table out once.
  • .trim() is the native string method. jQuery's old $.trim() is deprecated since 3.5 (see the utilities lesson), so new code calls .trim() on the value directly.
  • The hidden property is the cleanest way to hide a row, because it does not fight with the table's own display rules and it also removes the row from the accessibility tree.
  • role="status" makes the count a polite live region, so screen reader users hear "Showing 2 of 9 mountains" after typing without losing focus.

Sorting columns

Sorting reuses what you already have: the rows are in the DOM, and every cell remembers its value. A jQuery collection is array-like but not an array, and its own .sort() is an internal method you should not rely on. So take the plain array with .get(), sort it with the native sort(), and append the rows back. Appending an element that is already in the document moves it, so the rows are reordered without being rebuilt.

The comparison function depends on the column type. Numbers use subtraction; text uses localeCompare(), which respects accented letters. Each header advertises its type in a data-type attribute, and the direction toggles between ascending and descending, remembered in the standard aria-sort attribute on the header cell. That attribute is more than decoration: it is how assistive technology announces "sorted ascending".

Wrapping the header text in a <button> makes the sort control keyboard accessible without extra code. The click handler is delegated on the <thead>.

Sortable columns with aria-sort

You now have both halves. In a full page you would put them together: render the rows once, attach the filter and the sorter to the same $tbody, and run the filter after a sort so highlights stay. Because both features only reorder or hide the existing rows, they never interfere.

Where to go from here

  • Large tables. For a few hundred rows this approach is instant. For thousands, filter on the server (see real-world AJAX patterns) or render only the visible page.
  • Stable sort. Modern browsers sort stably, so sorting by "Country" first and then by "Height" keeps countries in height order within ties. Older engines did not guarantee it.
  • Numbers in text. If you ever sort text that contains numbers (such as "item 10"), pass { numeric: true } as the third argument of localeCompare().
  • Persisting the choice. The sandbox here has no storage, but in a real page you could keep the last sort in localStorage and apply it after rendering.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the table build cells with .text() instead of inserting strings with .html()?

    Data from a server is not trustworthy. .text() treats it purely as text, which removes the whole class of XSS problems that come from .html().
  2. 2. Why is the row collection turned into an array with .get() before sorting?

    A jQuery object is array-like, not an array. .get() returns a real array that supports sort(), and appending existing elements moves them into the new order.
  3. 3. What does highlighting with split(new RegExp("(" + query + ")", "i")) rely on?

    When split() receives a regex with a capturing group, the captured separators are included in the result array between the other pieces.
  4. 4. What is the purpose of the aria-sort attribute on the header cell?

    aria-sort only communicates state; your script does the sorting. Screen readers use it to announce that the column is sorted ascending or descending.
  5. 5. Before building the interface, why was the data wrapped in a function that returns a promise?

    A stand-in with the same interface as the real call lets you build and test the interface first, then swap the data source in one place.

Summary

  • Hide the data source behind a function that returns a promise; a stand-in lets you build the interface before a server exists.
  • Render with $("<tr>") and .text(), and keep raw values in .data() so filtering and sorting never parse the DOM.
  • Debounce the input handler, toggle the hidden property, and show an empty state and a live status message.
  • Highlight matches with split() and a capturing group, creating <mark> elements with .text(), and escape the query before building a regular expression.
  • Sort with the native sort() on .get(), append the rows to reorder them and report the direction with aria-sort.

The last project combines forms, validation and animation: Project: Multi-Step Form Wizard.