How to create a dynamic table with sorting and filtering using jQuery



Image not found!!

Creating a dynamic table with sorting and filtering using jQuery involves manipulating the HTML DOM elements and handling user interactions. Below is a simple example to get you started. This example assumes you have a basic knowledge of HTML, CSS, and jQuery.

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dynamic Table with Sorting and Filtering</title> <style> table { border-collapse: collapse; width: 100%; margin-top: 20px; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; cursor: pointer; } input { margin-bottom: 10px; } </style> </head> <body> <input type="text" id="filterInput" placeholder="Filter by Name"> <table id="dataTable"> <thead> <tr> <th data-column="name">Name</th> <th data-column="age">Age</th> <th data-column="country">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> <!-- Add more rows as needed --> </tbody> </table> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script> $(document).ready(function() { // Initial sorting column and order let sortColumn = 'name'; let sortOrder = 1; // Initial table setup sortTable(sortColumn, sortOrder); // Handle column header click for sorting $('th').click(function() { const column = $(this).data('column'); // Toggle sorting order if the same column is clicked sortOrder = (sortColumn === column) ? -sortOrder : 1; sortTable(column, sortOrder); }); // Handle filter input $('#filterInput').on('input', function() { const filterValue = $(this).val().toLowerCase(); filterTable(filterValue); }); function sortTable(column, order) { const tbody = $('tbody'); const rows = $('tr', tbody).toArray(); rows.sort(function(a, b) { const aValue = $(a).find('td[data-column="' + column + '"]').text(); const bValue = $(b).find('td[data-column="' + column + '"]').text(); if ($.isNumeric(aValue) && $.isNumeric(bValue)) { return (aValue - bValue) * order; } else { return aValue.localeCompare(bValue) * order; } }); tbody.empty().append(rows); sortColumn = column; } function filterTable(value) { const rows = $('tbody tr'); rows.filter(':contains("' + value + '")').show(); rows.not(':contains("' + value + '")').hide(); } // Case-insensitive :contains() pseudo-selector $.expr[":"].contains = $.expr.createPseudo(function(arg) { return function( elem ) { return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0; }; }); }); </script> </body> </html>

This example includes a simple table with columns for name, age, and country. Users can click on the column headers to sort the table based on the selected column, and a filter input is provided for filtering the table based on the name column. The script uses jQuery for DOM manipulation and event handling.