A2oz

How to Convert HTML Table to DataTable in jQuery?

Published in Web Development 2 mins read

You can easily transform your HTML table into a powerful and interactive DataTable using jQuery. Here's how:

1. Include jQuery and DataTables Libraries

First, you need to include the necessary jQuery and DataTables libraries in your HTML file. Add the following code within the <head> section:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>

2. Initialize DataTable

Once the libraries are included, you can initialize the DataTable using jQuery. Select your HTML table using its ID or class, and then call the DataTable() function:

$(document).ready(function() {
  $('#myTable').DataTable();
});

This code snippet will convert the table with the ID myTable into a DataTable.

3. Customize DataTable

DataTables offers extensive customization options to enhance its functionality and appearance. Here are a few examples:

  • Pagination: Add pagination to display data in chunks using paging: true.
  • Search: Enable searching within the table using searching: true.
  • Sorting: Allow users to sort columns by clicking the column headers using ordering: true.
  • Column Visibility: Control which columns are displayed using columns: [ { visible: false }, ... ].
  • Styling: Apply custom CSS to change the DataTable's appearance.

4. Example

Here's a complete example demonstrating the conversion and customization:

<!DOCTYPE html>
<html>
<head>
<title>HTML Table to DataTable</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
</head>
<body>

<table id="myTable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>City</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>John Doe</td>
      <td>30</td>
      <td>New York</td>
    </tr>
    <tr>
      <td>Jane Doe</td>
      <td>25</td>
      <td>London</td>
    </tr>
  </tbody>
</table>

<script>
$(document).ready(function() {
  $('#myTable').DataTable({
    paging: true,
    searching: true,
    ordering: true,
    columns: [
      { visible: true },
      { visible: true },
      { visible: true }
    ]
  });
});
</script>

</body>
</html>

This example demonstrates how to convert a basic HTML table into a DataTable with pagination, search, sorting, and column visibility controls.

Related Articles