In this guide, we’ll explore how to create an HTML table with sorting and filtering features using custom scripts and popular table libraries.
Advantages of Adding Sorting and Filtering to HTML Tables
Sorting and filtering features make HTML tables much more user-friendly, transforming them from simple, static displays into dynamic, interactive tools. Users can quickly locate what they need, whether it’s finding a specific item or identifying patterns in the data.
These enhancements also support better data analysis. Sorting reveals high and low values at a glance, while filtering allows users to isolate particular categories or attributes, making it easier to focus on the most relevant information in large datasets.
Technical Solutions to Add Sorting and Filtering to an HTML Table
JavaScript is necessary to make a table manually sortable and filterable with no delay for the user since HTML and CSS alone do not have the functionality to provide these features directly.
It is also possible to sort and filter a table using query parameters. However, this method relies on the server and doesn’t allow quick interactions with the table. Consequently, the solutions described in this tutorial will only use JavaScript-based implementations.
Sorting and Filtering Implementation
In this section, we will implement sorting and filtering using vanilla JavaScript.
Implementing Sorting
With plain JavaScript, you can implement basic sorting and filtering without relying on external libraries.
In this example, event listeners are added to the onclick event to execute the sortTable()
function when the table header cells are clicked. The parameter of the function is used to indicate the column to sort.
<table id="my-table">
<thead>
<tr>
<th onclick="sortTable(0)">Name</th>
<th onclick="sortTable(1)">Age</th>
<th onclick="sortTable(2)">Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>25</td>
<td>USA</td>
</tr>
<tr>
<td>Alice</td>
<td>30</td>
<td>UK</td>
</tr>
<tr>
<td>Maria</td>
<td>28</td>
<td>Spain</td>
</tr>
</tbody>
</table>
The sortTable()
function sorts the table data based on the provided column index.
/**
* Sorts the table with id equal to "my-table" based on the data available
* in the specified column.
*/
function sortTable(columnIndex) {
// Get the table rows and remove the header.
let table = document.getElementById("my-table");
let rows = Array.from(table.rows).slice(1);
// Generate the sorted rows.
let sortedRows = rows.sort((a, b) => {
let cellA = a.cells[columnIndex].innerText;
let cellB = b.cells[columnIndex].innerText;
return cellA.localeCompare(cellB);
});
// Update the table data.
sortedRows.forEach(row => table.tBodies[0].appendChild(row));
}
Here, we’ve created a table where clicking the header cells sorts the rows by the respective column. The sortTable()
function compares the values in each row and rearranges them accordingly.
Adding Filtering
To add filtering, you can use a search input that filters the rows based on user input. Here’s a simple way to do that.
First, add the same table used in the previous sorting example to the HTML document. Then, add an input field before the HTML table. This is the field used to search data in the table. Dynamic filtering is applied by running the filterTable()
function on the onkeyup
event.
<input type="text" id="filterInput" onkeyup="filterTable()" placeholder="Search for names..">
This table filtering function iterates over the table rows and hides the rows where the searched term is not present in the cells.
function filterTable() {
// Get the value in the search field.
let input = document.getElementById('filterInput');
let filter = input.value.toUpperCase();
// Get the rows of the table.
let table = document.getElementById('my-table');
let rows = table.getElementsByTagName('tr');
// Iterate over the rows.
for (let i = 1; i < rows.length; i++) {
// Get the cell in the iterated row.
let cells = rows[i].getElementsByTagName('td');
let match = false;
// Iterate over the cells. If there is a match in one of the cell, assign true to the dedicated match variable.
for (let j = 0; j < cells.length; j++) {
if (cells[j].innerText.toUpperCase().includes(filter)) {
match = true;
break;
}
}
// If there is a match, leave the row visible; otherwise, hide the row.
rows[i].style.display = match ? "" : "none";
}
}
When the user types in the search box, the filterTable()
function hides rows that don’t contain the input text in any column.
DataTables Library
DataTables is currently the most popular library for creating sortable and filterable HTML tables. It’s recommended because it’s easy to use and a complete feature set.
To start, create an HTML document and include a table with enough data to appreciate the filtering and sorting capabilities:
<table id="my-table" class="display">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>25</td>
<td>USA</td>
</tr>
<tr>
<td>Alice</td>
<td>30</td>
<td>UK</td>
</tr>
<tr>
<td>Maria</td>
<td>28</td>
<td>Spain</td>
</tr>
</tbody>
</table>
In the document head, include the necessary assets to load respectively jQuery (DataTables uses Jquery), the DataTables CSS style, and the DataTables library.
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
To initialize DataTables, add this script to the page head. With no configuration options passed, this basic initialization enables both filtering and sorting capabilities.
<script type="text/javascript">
$(document).ready(function () {
$('#my-table').DataTable();
});
</script>
To sort a table click the header cells. An arrow icon indicates sorting direction (ascending or descending) in the column header. Unsorted columns display a neutral double-arrow icon.
The search feature gives users the ability to find specific data quickly. When a search term is provided. The row is matched and shown in the result set if data is found in any column.
Sorting Options
As mentioned in the previous section, the DataTables sorting capabilities are enabled by default. We can, however, customize the sorting behavior with dedicated options.
For example, sorting can be turned on or off for an entire table using the ordering
property of the configuration object.
new DataTable('#my-table', {
ordering: false
});
It is also possible to turn on or off manual sorting for individual columns using the column orderable
property.
new DataTable('#my-table', {
columnDefs: [{orderable: false, targets: 0}]
});
You can also configure the initial sorting criteria. In this example, the table is sorted using the fourth column (targeted using the index 3), and the sorting order is set to descending (configured with the desc value).
new DataTable('#my-table', {
order: [[3, 'desc']]
});
Sorting can be further customized using sorting plugins and type-detection plugins. Note that in all table libraries, type detection is strictly correlated with sorting. Detecting the correct data type allows the library to apply the correct sorting function.
Filtering Options
Let’s now focus on searching options. These options allow to control aspects like the ability to search a table, the columns on which data should be searched, the aspect and behavior of the search box, and more.
Enabling and disabling the search feature
First of all, search is enabled by default in DataTables. You can turn it on or off if needed using the searching
property of the configuration object.
In the example below, searching is turned off.
new DataTable('#my-table', {
searching: false
});
Control the position of the search filter
By default, the field used to filter the table is positioned in the top right. However, you can customize its position using the layout options.
In the example below, we placed the search
input at the bottom right and set a custom placeholder for the search field.
new DataTable('#my-table', {
layout: {
topStart: 'info',
bottomEnd: {
search: {
placeholder: 'Search'
}
}
}
});
Search Only on Specific Columns
You can enable the search feature only in specific columns. For example, this option can be used in large or complex tables, where searching only in relevant columns (e.g., product name, customer ID) can prevent users from getting irrelevant results.
As we have seen from the first basic example, search is enabled in all columns by default. As a consequence, we can search on specific columns simply by disabling the feature in the columns where it’s not needed.
In this example, search is disabled in the columns indicated in the targets
property of the object; specifically, here search is disabled on the third column (targeted with the index 2):
new DataTable('#my-table', {
columnDefs: [{searchable: false, targets: 2}]
});
We can also use this alternative syntax. In this example, the search function was turned off in the first column.
new DataTable('#my-table', {
columns: [{searchable: false}, null, null, null, null]
});
To learn more about this subject, see the searchable
parameter in the library documentation.
TableSorter
Mottie Tablesorter is a lightweight jQuery plugin that enhances HTML tables with sorting and filtering capabilities. Ideal for small to medium datasets, it offers features like multi-column sorting, custom parser support, and column filtering, all while remaining easy to integrate. Perfect for developers needing efficient table manipulation without heavy dependencies.
To start with TableSorter, add the necessary assets in the HTML document head:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://mottie.github.io/tablesorter/js/jquery.tablesorter.min.js"></script>
<link rel="stylesheet" href="https://mottie.github.io/tablesorter/css/theme.default.css">
Get the table element using jQuery and initialize the library:
$(document).ready(function () {
$("#my-table").tablesorter();
});
Note: This library is a fork of the original TableSorter, which was abandoned a few years ago.
Other Table Libraries to Sort and Filter Data
While implementation details are not included in this tutorial, it’s worth mentioning these popular table libraries:
- Tabulator – A feature-rich JavaScript library for creating interactive tables with support for sorting, filtering, pagination, and more.
- Footable – A responsive table plugin built on jQuery and made for Bootstrap.
- ListJs – A lightweight JavaScript library that includes all the essential features used to make tables interactive.