jQuery DataTable plugin-Add a dropdown search filter to the table header
— jQuery, DataTable, Quick Tip — 2 min read
This tutorial will teach you how to add a dropdown or a <select>
input element in place of the header in a table configured with the jQuery DataTable plugin. Moreover, this dropdown will also act as a filter that will filter the rows based on the selected option.
Initial Setup
The initial setup is pretty basic with the table and a minimal DataTable initialization script.
Check out the code in jsFiddleSolution
What we're going to try and achieve is show a dropdown instead of the "Gender" header. It'll have three options: "All", "Male" and "Female". Clicking any option will filter the table rows accordingly.
Now to replace the header with a <select>
tag that will act as filter, we need to add the below script to the DataTable initialization statement.
$(document).ready(function() { $("table.my-table").DataTable({ // execute callback when DataTable is completely initialiazed "initComplete": function() { // Select the column whose header we need replaced using its index(0 based) this.api().column(2).every(function() { var column = this; // Put the HTML of the <select /> filter along with any default options var select = $('<select class="form-control input-sm"><option value="">All</option></select>') // remove all content from this column's header and // append the above <select /> element HTML code into it .appendTo($(column.header()).empty()) // execute callback when an option is selected in our <select /> filter .on('change', function() { // escape special characters for DataTable to perform search var val = $.fn.dataTable.util.escapeRegex( $(this).val() );
// Perform the search with the <select /> filter value and re-render the DataTable column .search(val ? '^' + val + '$' : '', true, false) .draw(); }); // populate options in the <select /> filter with unique values from the column's data column.data().unique().sort().each(function(d, j) { select.append("<option value='" + d + "'>" + d + "</option>") }); }); }, // disable sorting on the column with the filter in its header. "columnDefs": [{ targets: [2], orderable: false }] });});
Here is how it looks now:
Check out the code in jsFiddleWoo hoo!🎉 The dropdown filter works like a charm. Hope this helps!🙏