How to handle multiple rows selection using jQuery DataTables plugin?


Handling multiple rows selection in jQuery DataTables adds a powerful and intuitive interaction feature to your data tables. Whether you need to perform bulk actions, manipulate selected data, or simply provide a more user-friendly experience, the ability to select multiple rows simultaneously is invaluable.

In this blog post, we will explore how to handle multiple rows selection using the jQuery DataTables plugin. We will delve into the configuration options, event handling techniques, and customization possibilities that allow you to seamlessly incorporate this functionality into your web applications.

By the end of this article, you will have a solid understanding of how to enable and customize multiple rows selection in jQuery DataTables. You will be equipped with the knowledge and practical examples to implement this feature in your own projects, elevating the user experience and empowering users to interact with data tables in a more efficient and effective way.

Enabling Multiple Rows Selection

To enable multiple rows selection in jQuery DataTables, you need to configure the plugin with the appropriate options. Let's explore the steps to enable this functionality.

  • Initialization  Begin by initializing the DataTables plugin on your HTML table. Here's an example:

$('#myTable').DataTable();
  • Selectable Rows  By default, DataTables allows selecting individual rows. To enable multiple rows selection, you need to specify the selection mode. Add the select option to the DataTable initialization:

$('#myTable').DataTable({
   select: {
      style: 'multi'
   }
});
  • The style  'multi' option enables multiple rows selection. This means users can select multiple rows by holding the Ctrl or Shift key while clicking.

  • Visual Feedback  By default, DataTables provides visual feedback to indicate selected rows. You can customize the appearance of selected rows using CSS classes. The default class for selected rows is selected. You can modify or add your custom CSS classes to style the selected rows as desired.

.selected {
   background-color: #e0e0e0;
}
  • Update the CSS class according to your application's design requirements.

With these steps, you have successfully enabled multiple rows selection in jQuery DataTables. Users can now select multiple rows by clicking while holding the Ctrl or Shift key.

Example

Here’s how the full example would look like −

<!DOCTYPE html>
<html>
<head>
   <title>Multiple Rows Selection</title>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
   <style>
      .selected {
         background-color: #e0e0e0;
      }
   </style>
</head>
<body>
   <table id="myTable" class="display">
      <thead>
         <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Country</th>
         </tr>
      </thead>
      <tbody>
         <tr>
            <td>John Doe</td>
            <td>25</td>
            <td>USA</td>
         </tr>
         <tr>
            <td>Jane Smith</td>
            <td>30</td>
            <td>Canada</td>
        </tr>
        <tr>
            <td>Mark Johnson</td>
            <td>28</td>
            <td>Australia</td>
        </tr>
      </tbody>
   </table>   
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
   <script>
      $(document).ready(function() {
         $('#myTable').DataTable({
            select: {
               style: 'multi'
            }
         });
      });
   </script>
</body>
</html>

In this example, we have a simple HTML table with three columns: Name, Age, and Country. By initializing the DataTables plugin on the table with the select option set to style: 'multi', we enable multiple rows selection. The CSS class .selected is defined to style the selected rows with a light gray background color.

In the next section, we will explore how to handle the row selection events and perform actions based on the selected rows.

Handling Row Selection Events

Now that we have enabled multiple rows selection in jQuery DataTables, let's explore how to handle the row selection events and perform actions based on the selected rows.

  • Row Selection Event  jQuery DataTables provides an event called select that is triggered whenever a row is selected. You can listen to this event and execute your custom code. Here's an example of handling the row selection event and displaying the selected row data 

Example

<!DOCTYPE html>
<html>
<head>
   <title>Row Selection Event</title>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
</head>
<body>
   <table id="myTable" class="display">
      <thead>
         <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Country</th>
         </tr>
      </thead>
      <tbody>
         <tr>
            <td>John Doe</td>
            <td>25</td>
            <td>USA</td>
         </tr>
         <tr>
            <td>Jane Smith</td>
            <td>30</td>
            <td>Canada</td>
         </tr>
         <tr>
            <td>Mark Johnson</td>
            <td>28</td>
            <td>Australia</td>
         </tr>
      </tbody>
   </table>   
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
   <script>
      $(document).ready(function() {
         var table = $('#myTable').DataTable({
            select: {
               style: 'multi'
            }
         });
   
         table.on('select', function(e, dt, type, indexes) {
            if (type === 'row') {
               var data = dt.rows(indexes).data().toArray();
               console.log('Selected Rows:', data);
            }
         });
      });
   </script>
</body>
</html>

In this code, we use the on() method to attach a listener to the select event of the DataTable. The event callback receives parameters including the event object e, the DataTable instance dt, the selection type type, and the selected row indexes indexes. We check if the selection type is 'row' to ensure we're handling row selection events specifically. Then, we retrieve the data of the selected rows using the rows().data().toArray() method and log it to the console.

  • Deselection Event  Similarly, jQuery DataTables provides a deselect event that is triggered when a row is deselected. You can listen to this event to perform actions when a row is deselected.

Example

<!DOCTYPE html>
<html>
<head>
   <title>Deselection Event</title>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
</head>
<body>
   <table id="myTable" class="display">
      <thead>
         <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Country</th>
         </tr>
      </thead>
      <tbody>
         <tr>
            <td>John Doe</td>
            <td>25</td>
            <td>USA</td>
         </tr>
         <tr>
            <td>Jane Smith</td>
            <td>30</td>
            <td>Canada</td>
         </tr>
         <tr>
            <td>Mark Johnson</td>
            <td>28</td>
            <td>Australia</td>
         </tr>
      </tbody>
   </table>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
   <script>
      $(document).ready(function() {
         var table = $('#myTable').DataTable({
            select: {
               style: 'multi'
            }
         });
   
         table.on('deselect', function(e, dt, type, indexes) {
            if (type === 'row') {
               var data = dt.rows(indexes).data().toArray();
               console.log('Deselected Rows:', data);
            }
         });
      });
   </script>
</body>
</html>

In this code, we use the on() method to attach a listener to the deselect event of the DataTable. The event callback receives similar parameters as the select event. We check if the selection type is 'row', retrieve the data of the deselected rows, and log it to the console.

With these event handlers in place, you can capture row selection and deselection events in jQuery DataTables. You can perform various actions based on the selected or deselected rows, such as updating UI elements, manipulating data, or triggering other functions.

In the next section, we'll explore additional customization options for row selection, such as adding checkboxes and selecting all rows.

Customizing Row Selection Options

In addition to handling row selection events, jQuery DataTables provides various options for customizing the behavior and appearance of row selection. Let's explore some of these options −

  • Checkbox Selection  Checkbox selection allows users to select rows by clicking checkboxes associated with each row. This feature is useful when you want to provide a more explicit way for users to select rows. To enable checkbox selection, you can use the select option with the style set to 'multi' and the selector set to 'td:first-child input:checkbox'. Here's an example:

$('#myTable').DataTable({
   select: {
      style: 'multi',
      selector: 'td:first-child input:checkbox'
   }
});

In this code, we specify the selector 'td:first-child input:checkbox', which targets the checkboxes in the first column of each row. This ensures that clicking the checkboxes selects the corresponding rows.

  • Select All Rows  jQuery DataTables provides a built-in "Select All" checkbox that allows users to select or deselect all rows at once. To enable this feature, you can set the selectAll option to true:

$('#myTable').DataTable({
   select: {
      style: 'multi',
      selector: 'td:first-child input:checkbox',
      selectAll: true
   }
});

With selectAll set to true, a "Select All" checkbox will be added to the table header. Clicking this checkbox will select or deselect all rows in the table. You can customize the appearance and behavior of the "Select All" checkbox using CSS and the available options provided by jQuery DataTables.

By leveraging these customization options, you can enhance the row selection functionality in your DataTables implementation, providing a more interactive and user-friendly experience.

In the next section, we'll discuss additional features and techniques for working with multiple rows selection in jQuery DataTables.

Advanced Techniques for Multiple Rows Selection

In this section, we'll explore some advanced techniques and features that can further enhance the handling of multiple rows selection using jQuery DataTables.

  • Programmatic Selection − In addition to user interaction, you can also programmatically select or deselect rows using DataTables' API. The row().select() and row().deselect() methods allow you to select or deselect specific rows based on their indexes. Here's an example of programmatically selecting the first row:

var table = $('#myTable').DataTable();
table.row(0).select();

In this code, we obtain the DataTable instance using the DataTable() method and then use the row() method with the row index (0 in this case) to select the corresponding row.

  • Preselecting Rows  If you want to preselect certain rows when the table is initialized, you can use the selected option. The selected option accepts an array of row indexes to be initially selected.

$('#myTable').DataTable({
   select: {
      style: 'multi',
      selected: [1, 3, 5]
   }
});

In this example, rows with indexes 1, 3, and 5 will be preselected when the table is loaded.

  • Styling Selected Rows  You can apply custom styles to selected rows to visually distinguish them from other rows. DataTables automatically adds a selected class to the selected rows, which you can target with CSS to define your desired styles.

.selected {
   background-color: #f5f5f5;
   font-weight: bold;
}

In this CSS snippet, we set a background color and bold font weight for the selected rows.

  • Clearing Selection − To programmatically clear the selection of all rows, you can use the rows().deselect() method without any arguments.

var table = $('#myTable').DataTable();
table.rows().deselect();

This code deselects all rows in the table.

By utilizing these advanced techniques, you can have more control over row selection, preselect rows as needed, apply custom styles, and programmatically manipulate the selection based on your application's requirements.

Conclusion

In this blog post, we explored how to handle multiple rows selection using the jQuery DataTables plugin. We discussed various techniques and features that enable efficient management of row selection in DataTables.

We began by introducing the concept of row selection and its importance in enhancing the user experience. We then delved into the implementation details, covering topics such as handling selection events, customizing row selection options, and utilizing advanced techniques for programmatic selection and styling.

Updated on: 07-Aug-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements