Creating a custom filter on column level

Creating a custom filter on column level

shadow1lyshadow1ly Posts: 2Questions: 0Answers: 0

Creating a custom filter on column level

Define the Column names for the filter

var allowedTextFilters = ["Col1", "Col3"];
var allowedComboFilters = ["Col2"];

On Datatable

$('#dataTableId').DataTable({
"columns": ..
"data": ..
"initComplete": function () {
                createFilter(this.api(), "dataTableId", allowedTextFilters, allowedComboFilters)
            }
        });
function createFilter(dataTable, tableId, allowedTextFilters, allowedComboFilters) {
    var tableFilterRowId = tableId + "-filter-row";
    var tableFilterRow = $('#' + tableFilterRowId);
    if (!tableFilterRow.length) {
        tableFilterRow = $("<tr id='" + tableFilterRowId + "'role='row'>")
    }
    tableFilterRow.empty();

    dataTable.columns().every(function (index) {
        var column = this;
        var xid = tableId + "-" + index + "-filter";
        if (allowedTextFilters.includes(this.header().textContent)) {
            var th = $('<th>');
            th.appendTo(tableFilterRow)
            select = $('<input id="' + xid + '" class="form-control">')
                .appendTo(th)
                .on('input', function () {
                    column
                        .search($(this).val(), true, true, true)
                        .draw();
                });
        } else if (allowedComboFilters.includes(this.header().textContent)) {
            var th = $('<th>');
            th.appendTo(tableFilterRow)
            select = $('<select id="' + xid + '" class="form-select">')
                .appendTo(th)
                .on('change', function () {
                    column
                        .search("^" + $(this).val() + "$", true, true, true)
                        .draw();
                });
            select.empty();
            select.append('<option value="">---ALL---</option></select>');
                column.data().unique().sort().each(function (d, j) {
                    if (typeof (d) == "string" || typeof (d) == "boolean") {
                        select.append('<option value="' + d + '">' + d + "</option>");
                    }
                });
        } else {
            $('<th>').appendTo(tableFilterRow);
        }
    });
    tableFilterRow.appendTo('#' + tableId + ' thead');
}

Replies

  • allanallan Posts: 61,022Questions: 1Answers: 9,951 Site admin

    Hi,

    Thanks for your post, however, I'm not entirely clear if this is a question or a demonstration of how to do column filtering?

    Allan

  • shadow1lyshadow1ly Posts: 2Questions: 0Answers: 0

    This is a demonstration. sharing a generic plug n play logic for all data tables.

  • allanallan Posts: 61,022Questions: 1Answers: 9,951 Site admin

    Awesome - thanks for the clarification!

    Allan

Sign In or Register to comment.