Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

jQuery DataTables with Custom Client Side Filters

4.71/5 (4 votes)
22 Feb 2016CPOL4 min read 74.9K   2K  
This article gives an overview of using jQuery DataTables with custom filters for client side processing.

Introduction

In this article, I shall be explaining how to use jQuery DataTables with client side processing. There are many in built functionalities in DataTables but there are many applications where we might need some additional features. This tutorial helps with extending the functionalities with custom filters, checkbox, radio buttons, date range filters and textbox.

Background

jQuery dataTables has two options for processing, i.e., Client Side and Server Side Processing. Each of these options has its own pros and cons and are suitable to only few selected scenarios. Client Side processing can be used if the records to be processed are less than 10,000. The reason behind this is that we do not want the browser to be overloaded with data and perform slowly while loading and filtering the data. Server Side processing is more suitable for data with records more than 10,000. Although it makes a call to the database for every time any filteration is performed, it is quicker.

Let's Start

Here, we are using some predefined data hardcoded using HTML and performing custom filters using jQuery. I've tried to keep the code as simple as possible. To understand the tutorial, one needs to have a basic knowledge about HTML, jQuery, JavaScript and Bootstrap (Optional) jQuery DataTables offers a Textbox for filtering all the columns or those selected columns defined during initializing the table. But in this tutorial, I shall be extending some of the features of DataTables for some custom filters.

  1. Filtering data based on values of Radio buttons on one selected column
  2. Selecting columns for filtering and then searching using custom textbox
  3. Changing dataTable column's searchable feature based on requirements
  4. Filtering based on custom data range (Start Date and End Date)
  5. Search results highlight

Using the Code

As the data is hardcoded in HTML using Table tag, we shall not be discussing about it. Here is the screenshot of the data being used during the tutorial.

Image 1

Here is the jQuery Code to initialize it as a DataTable.

JavaScript
var table = $('#example').DataTable(
{
    "columnDefs": [
        {
            "targets": [3],
            "visible": true,
            "searchable": true,
            "type": "num"
        },
        {
            "targets": [2],
            "visible": true,
            "searchable": true,
            "type": "string"
        },
        {
            "targets": [1],
            "visible": true,
            "searchable": true,
            "type": "string"
        },
        {
            "targets": [0],
            "visible": true,
            "searchable": true,
            "type": "string"
        },
        {
            "aoColumns": [
      { "sName": "name" },
      { "sName": "position" },
      { "sName": "office" },
      { "sName": "age" },
      { "sName": "startdate" },
        { "sName": "salary" }
            ]
        }
    ]
});

Let's start with our features.

1. Selecting Columns for Filtering and Then Searching Using Custom Textbox

Image 2

Here, all the checkboxes represent the columns of the tables. Checkbox value represents that the column is searchable or not. There is an event listener to each of these checkboxes which re-initializes the dataTable. DataTable's property cannot be changed once it is set. Hence, we need to re-initialize the properties if we wish to change them. Here is the Event Listener on CheckBox Value Change.

JavaScript
$('.custom-checkbox').change(function () {
      changeTable(true);
});

function changeTable(checkBoxStatus) {
     i = 0;
     var arr = [];
     $('input:checkbox[name="searchby-column"]:checked').each(function () {
         arr[i++] = parseInt(this.value);
     });
     var searchBox = $('#customSearchTextBox').val();
     if (checkBoxStatus) {
         if (arr[0] == null) {
             arr = [0, 1, 2, 3, 4, 5];
         }
         table.destroy();
         table = $('#example').DataTable(
             {
                 "pagingType": "simple",
                 "iDisplayLength": 5,
                 "iDisplayStart": 1,
                 columnDefs: [
                    { targets: arr, searchable: true },
                    { targets: '_all', searchable: false }
                 ]
             }
         );
     }
     //use custom search box
     table.search(searchBox).draw();
 }

This code reinitializes the table and based on the textbox value, the table gets filtered.

JavaScript
$('#customSearchTextBox').on('keyup keypress change', function () {
    table.search(this.value).draw();
});

This chunk of code also helps in changing the searchable property of the table. Based on requirements, one can set which columns are to be searchable and which should not be.

2. Filtering Data Based On Values of Radio Buttons On One Selected Column

Image 3

Here, there are some pre-defined values for Positions. There is an event listener attached to these radio buttons.

JavaScript
('.customRadioButton').change(function () {
    table.columns(2).search(this.value).draw();
});

Here, we decided with which column to search, so we mentioned the index of column in our function.

3. Filtering Based on Custom Data Range (Start Date and End Date)

Many times, we come across requirements where we need to filter a table based on certain date range. Considering that situation, I came up with that code. It is not at all difficult.

First, we need to initialize the date picker based on our requirements.

JavaScript
$('.input-group.date').datepicker({
    format: "mm/dd/yy",
    orientation: "top left",
    autoclose: true,
    todayHighlight: false,
    toggleActive: false
});

Here is the code for event listener for date range.

JavaScript
$('#start-date, #end-date').change(function () {
    table.draw();
});

We are using custom jQuery Datatable function to perform filter for Date Range.

JavaScript
            $.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
    var startDate = Date.parse($('#start-date').val(), 10);
    var endDate = Date.parse($('#end-date').val(), 10);
    var columnDate = Date.parse(data[4]) || 0; // use data for the age column
    if ((isNaN(startDate) && isNaN(endDate)) ||
         (isNaN(startDate) && columnDate <= endDate) ||
         (startDate <= columnDate && isNaN(endDate)) ||
         (startDate <= columnDate && columnDate <= endDate)) {
        return true;
    }
    return false;
}
);

4. Search Results Highlight

There is a DataTable extension called Search Highlight which highlights the search results based on keywords in the textbox. Here is the JavaScript code to highlight the search results.

JavaScript
             //Hightlight our search text in the datatable
table.on('draw', function () {
    var body = $(table.table().body());
    //We can change the highlight color in dataTables.searchHighlight.css
    body.unhighlight();
    body.highlight(table.search());
});

If you wish to change the highlight color, there is a CSS file named dataTable.searchHighlight.css. Changing the color code in the file will change the highlight color.

JavaScript
table.dataTable span.highlight {
    background-color: yellow;
}

Points of Interest

Working on this small assignment really helped me understand the scope of DataTables and up to what extent it can be used. I believe that its functionalities can be further enhanced and it can prove to be the ultimate solution to faster table processing.

History

This is my first update on the project. I shall be playing around with DataTables more and try to enhance the functionality further.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)