Creating a Custom Date Range Filter in DataTables using JavaScript Tutorial
In this tutorial, you can learn how to create a Custom Date Range Filter in DataTables using JavaScript and DataTables Library's APIs. The tutorial aims to provide students and beginners with a reference for learning some techniques of using DataTables Library. Here, I will be providing a simple web page script that demonstrates the implementation of a custom date range in DataTables.
What is DataTables?
The DataTables is a jQuery JS Library Plugin for HTML Table. It is a very adaptable tool that adds all of these cutting-edge features to any HTML table and is based on the principles of progressive improvement.
What is a Date Range?
Date Range is a website or web application input field that is composed of dates from and to. These fields are often used for filtering the data to be shown on the user interface which has date data between the given 2 dates.
How to Create a Custom Date Range Filter in DataTable?
The Custom Date Range can be added to the DataTables container wrapper in many ways. We can even simply add the date input elements on the HTML script. Using the DataTables built-in APIs and event listener we can join the date range input values to the queries for getting the data using the Server-Side processing and Ajax API. We can simply add an event listener to the date range input field to update the dataTables data each time the date input value is updated. Check out the sample web application source code script that I created for this tutorial which demonstrates the creation of a custom date range for DataTables.
Sample Web Application
The script that will be provided below results in a simple web page that contains a table that is initiated with the DataTables plug-in/library. To test the source code on your local machine, kindly download and install a virtual web server with Apache and MySQL such as XAMPP/WAMP.
Database Schema
The sample web application I created using the following Database Schema and sample data. Open your PHPMyAdmin in your preferred browser and create a new database named sample_db. Then execute the following MySQL script on the created database.
- -- phpMyAdmin SQL Dump
- -- version 5.1.3
- -- https://www.phpmyadmin.net/
- --
- -- Host: 127.0.0.1
- -- Generation Time: Mar 17, 2023 at 06:20 AM
- -- Server version: 10.4.24-MariaDB
- -- PHP Version: 8.1.5
- --
- -- Database: `sample_db`
- --
- -- --------------------------------------------------------
- --
- -- Table structure for table `members`
- --
- --
- -- Dumping data for table `members`
- --
- --
- -- Indexes for dumped tables
- --
- --
- -- Indexes for table `members`
- --
- --
- -- AUTO_INCREMENT for dumped tables
- --
- --
- -- AUTO_INCREMENT for table `members`
- --
Database Connection
Next, the below is script is a PHP file script that handles the connection between the application and the database.
- <?php
- //Database Credentials
- $host = "localhost";
- $username = "root";
- $pw = "";
- $dbname = "sample_db";
- // Try to connect to database using the given DB credentials
- try{
- $conn = new MySQLi($host, $username, $pw, $dbname);
- if(!$conn){
- throw new ErrorException("Database Connection:". $conn->error, $conn->errno);
- }
- } catch (Exception $e){
- // Echo return message
- print($e->getMessage());
- die;
- }
Page Interface
Here's the HTML file script that contains the page layout and table element on the web page. The file is known as index.html. Note, the Bootstrap Framework, jQuery, and DataTables assets are loaded using CDN which requires an internet connection upon running even locally.
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="preconnect" href="https://fonts.googleapis.com">
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
- <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" />
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
- <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
- <link rel="stylesheet" href="style.css">
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
- </head>
- <body>
- <div class="content-md-lg py-3">
- <hr style="margin:auto; width:25px">
- <div class="col-lg-8 col-md-10 col-sm-12 col-12 mx-auto pt-4">
- <div class="card shadow rounded-0">
- <div class="card-body">
- <div class="rounded-0">
- <div class="container-fluid">
- <!-- Custom Date Range Inputs Wrapper -->
- <div class="row justify-content-center align-items-center flex-wrap mb-2">
- <div class="col-auto">
- </div>
- <div class="col-12 col-lg-3 col-md-4 col-sm-12">
- <input type="date" name="registered_from" class="form-control form-control-sm rounded-0">
- </div>
- <div class="col-auto">
- </div>
- <div class="col-12 col-lg-3 col-md-4 col-sm-12">
- <input type="date" name="registered_to" class="form-control form-control-sm rounded-0">
- </div>
- </div>
- <!-- Custom Date Range Inputs Wrapper -->
- <!-- Data Table -->
- <table class="table table-sm table-hover table-bordered table-striped" id="membersTbl">
- <thead>
- <tr>
- </tr>
- </thead>
- </table>
- <!-- Data Table -->
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
Stylesheet
Here is the CSS script of the custom design of the web page.
- @import url('https://fonts.googleapis.com/css2?family=Courgette&family=Secular+One&display=swap" rel="stylesheet');
- :root{
- --secular-font: 'Secular One', sans-serif;
- }
- *{
- box-sizing: border-box;
- }
- body *{
- font-family: 'Rubik', sans-serif;
- }
- /**
- Page Design
- */
- body,
- html{
- height: 100%;
- width: 100%;
- margin: 0;
- padding: 0;
- }
- body{
- background-color: #B9F3E4;
- }
- .page-title{
- font-size: 2.5rem;
- font-weight: 500;
- color: #fff;
- letter-spacing: 3px;
- font-family: var(--secular-font);
- text-align: center;
- text-shadow: 0px 0px 3px #2020208c;
- }
- .table-bordered>:not(caption)>*>* {
- border-width: 1px var(--bs-border-width);
- }
- .dataTables_wrapper>div{
- padding-bottom: .5em !important;
- }
JavaScript
Here's the JS file script that contains the codes that initiate dataTables and makes the custom date range input field functional.
- var membersDT;
- $(document).ready(function(){
- /**
- * Initializing DataTable
- * Load Data using Ajax
- */
- membersDT = $('#membersTbl').DataTable({
- processing: true,
- serverSide: true,
- columns:[
- {
- width:"20%",
- data:'date'
- },
- {
- width:"40%",
- data:'name'
- },
- {
- width:"20%",
- data:'email'
- },
- {
- width:"20%",
- data:'phone'
- }
- ],
- ajax: {
- method:'POST',
- url:'dt-query.php',
- data: {'registered_from' : $('input[name="registered_from"]').val(), 'registered_to' : $('input[name="registered_to"]').val() }
- },
- lengthMenu: [ [20, 50, -1], [20, 50, "All"] ]
- });
- membersDT.on('draw.dt', function(){
- /**
- * Add Event Listener to the custom inputs
- */
- $('input[name="registered_from"], input[name="registered_to"]').change(function(){
- //Update Ajax data
- membersDT.context[0].ajax.data = {'registered_from' : $('input[name="registered_from"]').val(), 'registered_to' : $('input[name="registered_to"]').val() }
- //Update DataTable data
- membersDT.draw();
- })
- })
- })
PHP Query
Here's the PHP file script that contains the source code for retrieving the data and filtered data from the database.
- <?php
- //Include Database Connection file script
- include_once('db-connect.php');
- //Table Column Name for oredring
- $columns_arr = ["abs(unix_timestamp(`date`))", "`name`", "`email`", "`phone`"];
- //Overall data rows count
- $total = $conn->query("SELECT id FROM `members`")->num_rows;
- $where = "";
- // Filter Statement if both Date Inputs are not empty
- $where .= " where ";
- $where .= " date_format(`date`, '%Y-%m-%d') BETWEEN '{$registered_from}' AND '{$registered_to}' ";
- }
- // Filter Statement if search value is not empty
- $where .= " where ";
- else
- $where .= " and ";
- $where .= " (date_format(`date`, '%F %d, %Y') LIKE '%{$search['value']}%' ";
- $where .= "OR `name` LIKE '%{$search['value']}%' ";
- $where .= "OR `email` LIKE '%{$search['value']}%' ";
- $where .= "OR `phone` LIKE '%{$search['value']}%') ";
- }
- // Query Order Statement
- $orderBy = " ORDER BY {$columns_arr[$order[0]['column']]} {$order[0]['dir']} ";
- // Query Order length or Limit Statement
- $limit = " LIMIT {$length} ";
- // Query Order start or offset Statement
- $offset = " OFFSET {$start} ";
- // default Filtered Data Row Value
- $totalFiltered = 0;
- // Data Query Statement
- $sql = "SELECT * FROM `members` {$where}";
- //Execution of Query with order, limit, and offset
- $qry = $conn->query($sql. "{$orderBy} {$limit} {$offset}");
- //Execution of Query with with where clause only
- $qryFiltered = $conn->query($sql);
- //Total Filtered Data Rows
- $totalFiltered =$qryFiltered->num_rows;
- // Default Data value
- $data = [];
- if($qry->num_rows > 0){
- // Data value
- $data =$qry->fetch_all(MYSQLI_ASSOC);
- foreach($data as $k => $row){
- // Update Date Format
- }
- }
- // Return the JSON data to datatables
- "draw" => $draw,
- "recordsTotal" => $total,
- "recordsFiltered" => $totalFiltered,
- "data" => $data
- ]);
- // close database connection
- $conn->close();
- ?>
Snapshots
Here are the snapshots of the overall result of the script I provided above.
DataTables Output
Filtered DataTables Output
There you go! I have also provided the complete source code zip file on this website and it is free to download. The download button is located below this tutorial's content. Feel free to download and do some experiments to enhance your knowledge of using DataTables Library.
That's it! I hope this Creating a Custom Date Range Filter in DataTables using JavaScript Tutorial will help you with what you are looking for and will be useful for your current and future web application projects.
Explore more on this website for more Tutorials and Free Source Codes.
Happy Coding =)
Comments
Add new comment
- Add new comment
- 1776 views