Custom sorting on values in a data-sort attribute with Jquery Datatables

Learn custom sorting on values in a data-sort attribute with jquery datatables with practical examples, diagrams, and best practices. Covers jquery, html, sorting development techniques with visual...

Custom Sorting DataTables by HTML Data Attributes

Hero image for Custom sorting on values in a data-sort attribute with Jquery Datatables

Learn how to implement custom sorting logic in jQuery DataTables using values stored in HTML5 data-sort attributes, enabling flexible and powerful table organization.

jQuery DataTables is a powerful plugin for enhancing HTML tables, offering features like pagination, searching, and sorting. While DataTables provides robust default sorting mechanisms, there are often scenarios where the visible content of a cell doesn't represent its true sortable value. For instance, you might display a formatted date (e.g., "Jan 1, 2023") but need to sort by its ISO 8601 equivalent (e.g., "2023-01-01"), or show a user-friendly status (e.g., "Pending") while sorting by an internal priority number. This article will guide you through implementing custom sorting using HTML5 data-sort attributes, allowing you to define a separate, hidden value specifically for sorting.

The Need for Custom Data-Sort Attributes

By default, DataTables sorts columns based on the visible text content within each <td> element. This works well for simple text or numeric data. However, when your display format differs from your desired sort order, direct text sorting can lead to incorrect results. Consider a column displaying prices with currency symbols, or dates formatted for readability. Sorting these directly as strings would yield lexicographical order, not numerical or chronological. The HTML5 data-* attribute provides an elegant solution by allowing you to embed a machine-readable sort value directly within the HTML element, separate from its visual representation.

flowchart TD
    A[HTML Table Cell] --> B{Visible Content}
    A --> C{Data-Sort Attribute}
    B -- Displayed to User --> D[User Interface]
    C -- Used by DataTables for Sorting --> E[Sorting Logic]
    E --> F[Sorted Table]

Separation of display content and sortable data using data-sort

Implementing Custom Sorting with data-sort

To leverage data-sort attributes for custom sorting, you need to configure DataTables to look for these attributes when sorting a specific column. This is achieved using the columns.data and columns.type options, or by defining a custom sorting plug-in. The data-sort attribute is particularly useful because DataTables has built-in support for it, simplifying the process significantly. You just need to ensure your HTML is structured correctly and then tell DataTables which column should use this attribute for sorting.

<table id="myDataTable">
    <thead>
        <tr>
            <th>Product Name</th>
            <th>Price</th>
            <th>Release Date</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Laptop Pro</td>
            <td data-sort="1200.00">$1,200.00</td>
            <td data-sort="2023-03-15">March 15, 2023</td>
        </tr>
        <tr>
            <td>Smartphone X</td>
            <td data-sort="750.50">$750.50</td>
            <td data-sort="2022-11-01">November 1, 2022</td>
        </tr>
        <tr>
            <td>Tablet Mini</td>
            <td data-sort="300.00">$300.00</td>
            <td data-sort="2023-01-20">January 20, 2023</td>
        </tr>
    </tbody>
</table>
$(document).ready(function() {
    $('#myDataTable').DataTable({
        "columnDefs": [
            { "type": "num-fmt", "targets": 1 }, // For price column (index 1)
            { "type": "date", "targets": 2 }    // For date column (index 2)
        ]
    });
});

Advanced Custom Sorting with columns.render and data-order

While data-sort is often sufficient, for more complex scenarios, especially when data is loaded via AJAX or needs dynamic formatting, DataTables offers the columns.render option. This allows you to define how data is displayed and how it's sorted separately. The data-order attribute (or _sort property in AJAX data) is the programmatic equivalent of data-sort when using columns.render or when providing data as objects. This approach gives you maximum flexibility, as you can transform the raw data into both a display format and a sortable format on the fly.

$(document).ready(function() {
    $('#myAdvancedDataTable').DataTable({
        "ajax": "data.json", // Assuming data.json provides objects with 'price' and 'releaseDate'
        "columns": [
            { "data": "productName" },
            {
                "data": "price",
                "render": {
                    "display": function (data, type, row) {
                        return '$' + parseFloat(data).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                    },
                    "sort": function (data, type, row) {
                        return parseFloat(data); // Sort by raw numeric value
                    }
                }
            },
            {
                "data": "releaseDate",
                "render": {
                    "display": function (data, type, row) {
                        return new Date(data).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
                    },
                    "sort": function (data, type, row) {
                        return new Date(data).getTime(); // Sort by timestamp
                    }
                }
            }
        ]
    });
});