SyntaxStudy
Sign Up
jQuery Advanced 5 min read

Sortable Data Table

Sortable Table

Add click-to-sort columns to any HTML table with jQuery, using a data attribute to track sort state.

Example
$("th[data-sort]").css("cursor","pointer").on("click", function() {
  const col = $(this).data("sort");
  const asc = $(this).data("asc") !== true;
  $(this).data("asc", asc).text($(this).text().replace(/[▲▼]/, "") + (asc ? " ▲" : " ▼"));
  const $tbody = $(this).closest("table").find("tbody");
  const rows = $tbody.find("tr").toArray();
  rows.sort((a, b) => {
    const av = $(a).find(`td[data-col=${col}]`).text();
    const bv = $(b).find(`td[data-col=${col}]`).text();
    return asc ? av.localeCompare(bv, undefined, { numeric: true }) : bv.localeCompare(av, undefined, { numeric: true });
  });
  $tbody.append(rows);
});
Pro Tip

localeCompare with numeric: true sorts "10" after "9" correctly — string sort would put "10" before "9".