Simple JavaScript Techniques for Building Sortable and Filterable Tables

·

3 min read

Interactive tables are an essential component of modern web applications. They allow users to view, sort, and filter data efficiently. By adding simple JavaScript functionality, you can transform static tables into dynamic, user-friendly interfaces. Fsiblog guide you, we’ll guide you through creating a sortable and filterable table using plain JavaScript.

Why Build Sortable and Filterable Tables?

Tables often display large datasets. Without sorting and filtering options, users may struggle to find relevant information. Adding these features enhances usability, improves accessibility, and creates a more professional user experience.

Prerequisites

To follow this guide, you should have basic knowledge of:

  • HTML and CSS for structuring and styling your table.

  • JavaScript basics for adding interactivity.

Step 1: Create the HTML Structure

Start by creating the basic table structure in HTML.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sortable and Filterable Table</title>
  <style>
    table {
      width: 100%;
      border-collapse: collapse;
    }
    th, td {
      border: 1px solid #ccc;
      padding: 8px;
      text-align: left;
    }
    th {
      cursor: pointer;
    }
    input[type="text"] {
      margin-bottom: 10px;
      padding: 5px;
      width: 100%;
      box-sizing: border-box;
    }
  </style>
</head>
<body>
  <h1>Sortable and Filterable Table</h1>
  <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="city">City</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John Doe</td>
        <td>25</td>
        <td>New York</td>
      </tr>
      <tr>
        <td>Jane Smith</td>
        <td>30</td>
        <td>Los Angeles</td>
      </tr>
      <tr>
        <td>Emily Johnson</td>
        <td>35</td>
        <td>Chicago</td>
      </tr>
      <tr>
        <td>Michael Brown</td>
        <td>40</td>
        <td>Houston</td>
      </tr>
    </tbody>
  </table>

  <script src="script.js"></script>
</body>
</html>

Step 2: Add Sorting Functionality

Create a JavaScript file (script.js) to handle sorting. Sorting can be toggled between ascending and descending for each column.

// Get table and headers
const table = document.getElementById('dataTable');
const headers = table.querySelectorAll('th');
let sortDirection = 1; // 1 for ascending, -1 for descending

headers.forEach(header => {
  header.addEventListener('click', () => {
    const column = header.dataset.column;
    const rows = Array.from(table.querySelectorAll('tbody tr'));

    rows.sort((a, b) => {
      const aText = a.querySelector(`td:nth-child(${header.cellIndex + 1})`).textContent.trim();
      const bText = b.querySelector(`td:nth-child(${header.cellIndex + 1})`).textContent.trim();

      if (!isNaN(aText) && !isNaN(bText)) {
        return sortDirection * (parseFloat(aText) - parseFloat(bText));
      } else {
        return sortDirection * aText.localeCompare(bText);
      }
    });

    // Append sorted rows
    const tbody = table.querySelector('tbody');
    rows.forEach(row => tbody.appendChild(row));

    // Toggle sort direction
    sortDirection *= -1;
  });
});

Step 3: Add Filtering Functionality

Enable filtering by capturing the input text and displaying only rows that match the query.

const filterInput = document.getElementById('filterInput');
filterInput.addEventListener('input', () => {
  const filterValue = filterInput.value.toLowerCase();
  const rows = table.querySelectorAll('tbody tr');

  rows.forEach(row => {
    const cellText = row.querySelector('td').textContent.toLowerCase();
    if (cellText.includes(filterValue)) {
      row.style.display = '';
    } else {
      row.style.display = 'none';
    }
  });
});

Step 4: Test Your Table

Now you have a fully functional table! Try clicking on the headers to sort by name, age, or city, and use the filter input to search for specific names.

Additional Enhancements

  1. Highlight Sorted Column: Add CSS classes to highlight the column being sorted.

  2. Debounce Filtering: Optimize the filtering function by debouncing input events.

  3. Pagination: Implement pagination for large datasets to improve performance.

  4. Responsive Design: Ensure the table works well on different screen sizes.

Conclusion

Creating a sortable and filterable table with JavaScript is straightforward and enhances the user experience significantly. By following this guide, you can integrate these features into your projects with ease. Experiment with additional features and share your creations!