How to handle events using jQuery DataTables plugin?


jQuery DataTables is a powerful plugin that provides advanced features for displaying and manipulating tabular data on the web. It offers a rich set of functionalities, including sorting, searching, pagination, and more. While DataTables simplifies the process of creating dynamic tables, effectively handling events within these tables is crucial to enhance user interactions and customize behavior.

In this blog post, we will explore how to handle events using the jQuery DataTables plugin. We'll dive into both basic and advanced event handling techniques that will enable you to respond to user actions, perform custom operations, and create interactive data tables.

Setting Up JQuery DataTables

Before we delve into event handling in jQuery DataTables, let's start by setting up the plugin in your web project. Follow these steps to get started −

  • Download the jQuery DataTables plugin  Visit the official DataTables website (https://datatables.net/) and download the latest version of the plugin. Alternatively, you can use a package manager like npm or include the CDN link in your HTML file.

  • Include the necessary dependencies  jQuery DataTables requires jQuery to be included in your project. Make sure to include the jQuery library before including the DataTables plugin.

  • Initialize the DataTable  To create a basic DataTable, target an HTML table element and call the .DataTable() method on it. You can provide options and customize the behavior of the DataTable as per your requirements.

Example

Here's an example of setting up a basic DataTable −

<!DOCTYPE html>
<html>
<head>
   <title>jQuery DataTables Event Handling</title>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.2/css/jquery.dataTables.min.css">
</head>
<body>
   <table id="myTable">
      <thead>
         <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Country</th>
         </tr>
      </thead>
      <tbody>
         <tr>
            <td>John Doe</td>
            <td>30</td>
            <td>USA</td>
         </tr>
         <tr>
            <td>Jane Smith</td>
            <td>25</td>
            <td>Canada</td>
         </tr>
         <!-- More table rows -->
      </tbody>
   </table>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://cdn.datatables.net/1.11.2/js/jquery.dataTables.min.js"></script>
   <script>
      $(document).ready(function() {
         $('#myTable').DataTable();
      });
   </script>
</body>
</html>

In this example, we have included the necessary CSS and JavaScript files for jQuery DataTables. The #myTable element is targeted and initialized as a DataTable. By default, DataTables will enhance the table with sorting, searching, and pagination features.

Once you have set up jQuery DataTables in your project, you can proceed to handle various events and customize the behavior according to your needs.

Basic Event Handling

jQuery DataTables provides several built-in events that allow you to handle user interactions and perform actions based on those events. In this section, we'll cover some of the basic event handling techniques you can utilize with DataTables.

Handling Click Events

Click events are commonly used to capture user interactions and trigger specific actions. DataTables provides two primary click events that you can handle −

  • Row Click Event − This event occurs when a user clicks on a table row. You can capture this event to perform actions such as highlighting the selected row, displaying additional details, or navigating to another page.

Example

Here's an example of handling the row click event −

<!DOCTYPE html>
<html>
<head>
   <title>Handling Row Click Event in jQuery DataTables</title>
   <link rel="stylesheet" type="text/css" href=  "https://cdn.datatables.net/1.11.2/css/jquery.dataTables.min.css">
</head>
<body>
   <table id="myTable">
      <thead>
         <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Country</th>
         </tr>
      </thead>
      <tbody>
         <tr>
            <td>John Doe</td>
            <td>30</td>
            <td>USA</td>
         </tr>
         <tr>
            <td>Jane Smith</td>
            <td>25</td>
            <td>Canada</td>
         </tr>
         <!-- More table rows -->
      </tbody>
   </table>   
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://cdn.datatables.net/1.11.2/js/jquery.dataTables.min.js"></script>
   <script>
      $(document).ready(function() {
         $('#myTable').DataTable();
   
         $('#myTable').on('click', 'tbody tr', function() {
            var rowData = $(this).find('td').map(function() {
               return $(this).text();
            }).get();
   
            console.log('Clicked row data:', rowData);
            // Perform actions based on the clicked row data
         });
      });
   </script>
</body>
</html>

In this example, we bind the click event to the tbody tr elements within the #myTable DataTable. When a user clicks on a table row, the event handler function is executed. Inside the event handler, we extract the data from the clicked row by finding the td elements and mapping their text values into an array. The row data is then logged to the console.

  • Cell Click Event − This event occurs when a user clicks on a specific cell within a table. You can use this event to perform actions based on the cell clicked, such as editing the cell value, showing a context menu, or triggering a custom operation.

Example

Here's an example of handling the cell click event -

<!DOCTYPE html>
<html>
<head>
   <title>Handling Cell Click Event in jQuery DataTables</title>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.2/css/jquery.dataTables.min.css">
</head>
<body>
   <table id="myTable">
      <thead>
         <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Country</th>
         </tr>
      </thead>
      <tbody>
         <tr>
            <td>John Doe</td>
            <td>30</td>
            <td>USA</td>
         </tr>
         <tr>
            <td>Jane Smith</td>
            <td>25</td>
            <td>Canada</td>
         </tr>
         <!-- More table rows -->
      </tbody>
   </table>   
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://cdn.datatables.net/1.11.2/js/jquery.dataTables.min.js"></script>
   <script>
      $(document).ready(function() {
         $('#myTable').DataTable();
   
         $('#myTable').on('click', 'tbody td', function() {
            var cellData = $(this).text();
   
            console.log('Clicked cell data:', cellData);
            // Perform actions based on the clicked cell data
         });
      });
   </script>
</body>
</html>

In this example, we bind the click event to the tbody td elements within the #myTable DataTable. When a user clicks on a cell, the event handler function is executed. Inside the event handler, we retrieve the text content of the clicked cell using $(this).text() and log it to the console.

By capturing row and cell click events, you can create interactive experiences within your DataTables and respond to user actions effectively.

Handling Search Events

The DataTables plugin also provides events related to searching and filtering data. These events allow you to capture search queries, perform custom operations based on the search input, and respond dynamically to changes in search results.

Example

Here's an example of capturing the search event and performing a custom action -

<!DOCTYPE html>
<html>
<head>
   <title>Capturing Search Event in jQuery DataTables</title>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.2/css/jquery.dataTables.min.css">
</head>
<body>
   <table id="myTable">
      <thead>
         <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Country</th>
         </tr>
      </thead>
      <tbody>
         <tr>
            <td>John Doe</td>
            <td>30</td>
            <td>USA</td>
         </tr>
         <tr>
            <td>Jane Smith</td>
            <td>25</td>
            <td>Canada</td>
         </tr>
         <!-- More table rows -->
      </tbody>
   </table>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://cdn.datatables.net/1.11.2/js/jquery.dataTables.min.js"></script>
   <script>
      $(document).ready(function() {
         var table = $('#myTable').DataTable();
   
         table.on('search.dt', function(e, settings) {
            var searchValue =    settings.oPreviousSearch.sSearch;
   
            console.log('Search value:', searchValue);
            // Perform custom action based on the search value
         });
      });
  </script>
</body>
</html>

In this example, we bind the search.dt event to the #myTable DataTable. The event is triggered whenever a search is performed on the DataTable. The event handler function receives the event object e and the DataTable settings object settings. We extract the search value from the settings object using settings.oPreviousSearch.sSearch and log it to the console. You can then perform custom actions based on the search value.

Advanced Event Handling

In addition to the basic event handling techniques covered in the previous section, jQuery DataTables provides advanced event handling options that allow you to further customize the behavior of your data tables. In this section, we'll explore two commonly used advanced event handling scenarios: sorting events and pagination events.

Sorting Events

Sorting is a fundamental feature of DataTables that allows users to order the table data based on specific columns. You can capture sorting events to perform additional actions or apply custom logic when the sorting state changes.

jQuery DataTables provides two sorting-related events −

  • Order Event − This event is triggered whenever the sorting order of one or more columns changes. You can use this event to perform actions such as updating data based on the new sorting order or refreshing related components.

Example

Here's an example of handling the Order event -

<!DOCTYPE html>
<html>
<head>
   <title>Order Event Example</title>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.2/css/jquery.dataTables.min.css">
</head>
<body>
   <table id="myTable">
      <thead>
         <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Country</th>
         </tr>
      </thead>
      <tbody>
         <tr>
            <td>John Doe</td>
            <td>30</td>
            <td>USA</td>
         </tr>
         <tr>
            <td>Jane Smith</td>
            <td>25</td>
            <td>Canada</td>
         </tr>
         <!-- More table rows -->
      </tbody>
   </table>   
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://cdn.datatables.net/1.11.2/js/jquery.dataTables.min.js"></script>
   <script>
      $(document).ready(function() {
         var table = $('#myTable').DataTable();
   
         table.on('order.dt', function(e, settings) {
            var sortedColumns = settings.aaSorting;
            console.log('Sorted columns:', sortedColumns);
            // Perform actions based on the sorted columns
         });
      });
   </script>
</body>
</html>

In this example, we bind the order.dt event to the #myTable DataTable. The event is triggered whenever the sorting order changes. The event handler function receives the event object e and the DataTable settings object settings. We extract the sorted columns information from settings.aaSorting and log it to the console. You can then perform custom actions based on the sorted columns.

  • Sort Event − This event is triggered when a single column's sorting order changes. You can use this event to perform specific actions related to the sorted column, such as updating the UI or triggering additional operations.

Example

Here's an example of handling the sort -

<!DOCTYPE html>
<html>
<head>
   <title>Sort Event Example</title>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.2/css/jquery.dataTables.min.css">
</head>
<body>
   <table id="myTable">
      <thead>
         <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Country</th>
         </tr>
      </thead>
      <tbody>
         <tr>
            <td>John Doe</td>
            <td>30</td>
            <td>USA</td>
         </tr>
         <tr>
            <td>Jane Smith</td>
            <td>25</td>
            <td>Canada</td>
         </tr>
         <!-- More table rows -->
      </tbody>
   </table>   
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://cdn.datatables.net/1.11.2/js/jquery.dataTables.min.js"></script>
   <script>
      $(document).ready(function() {
         var table = $('#myTable').DataTable();
   
         table.on('order.dt', function(e, settings) {
            var sortedColumn = settings.aaSorting[0][0];
            var sortDirection = settings.aaSorting[0][1];
            console.log('Sorted column:', sortedColumn);
            console.log('Sort direction:', sortDirection);
            // Perform actions based on the sorted column and direction
         });
      });
   </script>
</body>
</html>

In this example, we bind the order.dt event to the #myTable DataTable. The event is triggered when the sorting order changes. Inside the event handler function, we extract the sorted column and its sort direction from settings.aaSorting and log them to the console. You can then perform custom actions based on the sorted column and direction.

Pagination Events

Pagination allows users to navigate through different pages of data in a DataTable. jQuery DataTables provides pagination events that you can handle to perform actions when the pagination state changes.

The pagination-related events are as follows −

  • Page Change Event − This event is triggered when the user navigates to a different page. You can use this event to update the UI, fetch additional data for the new page, or trigger other related operations.

Example

Here's an example of handling the page Change event -

<!DOCTYPE html>
<html>
<head>
   <title>Page Change Event Example</title>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.2/css/jquery.dataTables.min.css">
</head>
<body>
   <table id="myTable">
      <thead>
         <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Country</th>
         </tr>
      </thead>
      <tbody>
         <!-- Large number of table rows -->
      </tbody>
   </table>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://cdn.datatables.net/1.11.2/js/jquery.dataTables.min.js"></script>
   <script>
      $(document).ready(function() {
         var table = $('#myTable').DataTable();
   
         table.on('page.dt', function(e, settings) {
            var currentPage = settings._iDisplayStart / settings._iDisplayLength + 1;
            console.log('Current page:', currentPage);
            // Perform actions based on the current page
         });
      });
   </script>
</body>
</html>

In this example, we bind the page.dt event to the #myTable DataTable. The event is triggered when the page changes. Inside the event handler function, we calculate the current page based on the display start and display length properties of the settings object and log it to the console. You can then perform custom actions based on the current page.

  • Page Length Change Event − This event is triggered when the user changes the number of rows displayed per page. You can use this event to adapt the UI or adjust data fetching strategies based on the new page length.

Example

Here's an example of handling the page length Change event.

<!DOCTYPE html>
<html>
<head>
   <title>Page Length Change Event Example</title>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.2/css/jquery.dataTables.min.css">
</head>
<body>
   <table id="myTable">
      <thead>
         <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Country</th>
         </tr>
      </thead>
      <tbody>
         <!-- Large number of table rows -->
      </tbody>
   </table>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://cdn.datatables.net/1.11.2/js/jquery.dataTables.min.js"></script>
   <script>
      $(document).ready(function() {
         var table = $('#myTable').DataTable();
   
         table.on('length.dt', function(e, settings, len) {
            console.log('New page length:', len);
            // Perform actions based on the new page length
         });
      });
   </script>
</body>
</html>

In this example, we bind the length.dt event to the #myTable DataTable. The event is triggered when the page length changes. The event handler function receives the event object e, the DataTable settings object settings, and the new page length value len. We log the new page length to the console. You can then perform custom actions based on the new page length.

Conclusion

In this blog post, we explored how to handle events using the jQuery DataTables plugin. We learned about the basic event handling techniques and advanced scenarios like sorting and pagination events. By leveraging these event handlers, you can customize the behavior of your DataTables, enhance user interactions, and perform additional actions based on user interactions.

Updated on: 07-Aug-2023

714 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements