Lädt...


🔧 How to Apply Sorting on Tables in HTML Using JavaScript: Sortable Paginated Tables


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

Introduction

Tables are a fundamental component of web development, often used to present data in a structured format. However, when dealing with large datasets, managing and navigating through the information can become challenging. This is where sorting and pagination come into play. In this blog post, we'll explore how to implement sorting functionality on HTML tables using JavaScript, creating sortable and paginated tables for better data organization and user experience.

Prerequisites

Before diving into the implementation, it's helpful to have a basic understanding of HTML, CSS, and JavaScript. Familiarity with DOM manipulation and event handling in JavaScript will be particularly beneficial. Additionally, ensure you have a text editor and a web browser installed to test your code.

Understanding Sortable and Paginated Tables

Sortable tables allow users to rearrange the rows based on specific criteria, such as alphabetical order, numerical value, or date. Pagination, on the other hand, involves dividing large datasets into manageable chunks or pages, enhancing readability and performance. By combining these functionalities, we can create user-friendly tables that facilitate efficient data exploration and analysis.

Implementing Sorting in HTML Tables

To implement sorting on an HTML table, we'll utilize JavaScript to add event listeners to the table headers. When a header is clicked, we'll dynamically sort the table rows based on the corresponding column's values. Let's illustrate this with an example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sortable Table</title>
    <script src="script.js" defer></script>
</head>
<body>
    <table id="data-table">
        <thead>
            <tr>
                <th onclick="sortTable(0)">ID</th>
                <th onclick="sortTable(1)">Name</th>
                <th onclick="sortTable(2)">Age</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>Nilesh</td>
                <td>25</td>
            </tr>
            <tr>
                <td>2</td>
                <td>SpeakLouder</td>
                <td>30</td>
            </tr>
            <tr>
                <td>3</td>
                <td>Raut</td>
                <td>20</td>
            </tr>
 <tr>
                <td>4</td>
                <td>Dev</td>
                <td>43</td>
            </tr>
        </tbody>
    </table>
</body>
</html>

In this example, each table header (<th>) has an onclick attribute calling a JavaScript function sortTable() with the column index as an argument. The sortTable() function will sort the rows based on the clicked column.

JavaScript Code for Sorting

Now, let's implement the sortTable() function in our script.js file:

function sortTable(columnIndex) {
    let table, rows, switching, i, x, y, shouldSwitch;
    table = document.getElementById("data-table");
    switching = true;

    while (switching) {
      switching = false;
      rows = table.rows;

      for (i = 1; i < rows.length - 1; i++) {
        shouldSwitch = false;
        x = rows[i].getElementsByTagName("td")[columnIndex];
        y = rows[i + 1].getElementsByTagName("td")[columnIndex];

        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
          shouldSwitch = true;
          break;
        }
      }

      if (shouldSwitch) {
        rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
        switching = true;
      }
    }
}

This JavaScript function performs a simple bubble sort algorithm to arrange the rows based on the values in the specified column.

Deafault Table

Default Table before sorting

Clicked on the column Label age , it sort the column according to age in decreasing order

Sorted Table based on age

Table Sorting using React js

import React, { useState } from 'react';

const SortTable = () => {
    const [data, setData] = useState([
        { id: 1, name: 'Nilesh', age: 25 },
        { id: 2, name: 'SpeakLouder', age: 30 },
        { id: 3, name: 'Raut', age: 20 },
         { id: 4, name: 'Devto', age: 21 }
    ]);
    const [sortBy, setSortBy] = useState('');
    const [sortOrder, setSortOrder] = useState('asc');

    const handleSort = (column) => {
        const order = column === sortBy && sortOrder === 'asc' ? 'desc' : 'asc';
        setData(prevData => {
            const sortedData = [...prevData].sort((a, b) => {
                if (a[column] < b[column]) return order === 'asc' ? -1 : 1;
                if (a[column] > b[column]) return order === 'asc' ? 1 : -1;
                return 0;
            });
            return sortedData;
        });
        setSortBy(column);
        setSortOrder(order);
    };

    return (
        <table>
            <thead>
                <tr>
                    <th onClick={() => handleSort('id')}>ID</th>
                    <th onClick={() => handleSort('name')}>Name</th>
                    <th onClick={() => handleSort('age')}>Age</th>
                </tr>
            </thead>
            <tbody>
                {data.map(item => (
                    <tr key={item.id}>
                        <td>{item.id}</td>
                        <td>{item.name}</td>
                        <td>{item.age}</td>
                    </tr>
                ))}
            </tbody>
        </table>
    );
};

export default SortTable;

Conclusion

In this blog post, we've learned how to apply sorting functionality to HTML tables using JavaScript, enabling users to interactively organize and explore data. By incorporating pagination techniques and responsive design principles, we can further enhance the usability and performance of our web applications. So go ahead, implement sortable and paginated tables to streamline data presentation and improve user experience!

For more advanced sorting algorithms and techniques, you can explore resources such as this article.

Remember, mastering the art of table manipulation opens up endless possibilities for creating dynamic and user-friendly web interfaces. Experiment with different features and customization options to tailor the tables to your specific needs and preferences. Happy coding!

...

🔧 How to Apply Sorting on Tables in HTML Using JavaScript: Sortable Paginated Tables


📈 130.16 Punkte
🔧 Programmierung

🔧 Power BI Paginated Reports: Creating and Using Paginated Reports for Detailed Reporting Needs


📈 57.4 Punkte
🔧 Programmierung

🔧 Bubble Sorting, Insertion Sorting & Selection Sort Algorithm Using Javascript


📈 46.9 Punkte
🔧 Programmierung

🔧 TypeID-JS: Type Safe, K-Sortable Unique IDs for Javascript


📈 37.59 Punkte
🔧 Programmierung

🔧 HTML Tables: how to create and style tables with HTML


📈 34.59 Punkte
🔧 Programmierung

🐧 Apply Yaml Manifest Using “kubectl apply”


📈 31.96 Punkte
🐧 Linux Tipps

🔧 17 Free Open-source Icon Libraries (Carefully Curated List, Filterable & Sortable) - Need Feedback


📈 31.18 Punkte
🔧 Programmierung

🔧 React Custom Hook Controller Pattern: Creating a Sortable Table


📈 31.18 Punkte
🔧 Programmierung

🔧 How to Create a Sortable and Filterable Table in React


📈 31.18 Punkte
🔧 Programmierung

🔧 An ETL Job using AWS Glue Studio to inner join DynamoDB tables, Apply Queries and Store the result in S3


📈 30.97 Punkte
🔧 Programmierung

🔧 Lazy Loading and Sorting for PrimeNG Tables


📈 30.59 Punkte
🔧 Programmierung

🔧 Lazy Loading and Sorting for PrimeNG Tables


📈 30.59 Punkte
🔧 Programmierung

🔧 Using Mapping Tables to Merge Data with Auto-Number Keys Referenced by Other Tables


📈 29.98 Punkte
🔧 Programmierung

🔧 Recap the highlight of the sorting algorithms using JavaScript for beginners


📈 28.98 Punkte
🔧 Programmierung

🐧 How to Use Pagination on HTML Tables Using JavaScript


📈 28.35 Punkte
🐧 Linux Tipps

📰 Power BI Paginated Reports June 2019 Feature Update Summary


📈 26.38 Punkte
📰 IT Nachrichten

📰 Announcing Paginated Reports in Power BI general availability


📈 26.38 Punkte
📰 IT Nachrichten

📰 Report Parameter Support for Paginated Report E-Mail Subscriptions are Now Available


📈 26.38 Punkte
📰 IT Nachrichten

📰 Enhanced Attachment Support for Paginated Reports E-Mail Subscriptions is Now Available


📈 26.38 Punkte
📰 IT Nachrichten

🕵️ Bug fix for paginated page links for com_finder and com_content archive


📈 26.38 Punkte
🕵️ Sicherheitslücken

🔧 Supercharge Your Paginated Reports with DAX in Power BI Report Builder


📈 26.38 Punkte
🔧 Programmierung

📰 Simplified Reporting: Paginated Reports via Power BI Report Builder


📈 26.38 Punkte
📰 IT Security Nachrichten

🐧 Mastering Power BI Report Builder: A Comprehensive Guide to Paginated Reports


📈 26.38 Punkte
🐧 Linux Tipps

📰 Embed paginated reports in your own application for your customers (Preview)


📈 26.38 Punkte
📰 IT Nachrichten

📰 Paginated Reports in Power BI September 2019 Feature Summary


📈 26.38 Punkte
📰 IT Nachrichten

📰 URL parameters for Paginated Reports are now available


📈 26.38 Punkte
📰 IT Nachrichten

📰 Storytelling with Tables Part 1: Tables with Plotly


📈 25.35 Punkte
🔧 AI Nachrichten

🕵️ Low CVE-2015-9401: Websimon-tables project Websimon-tables


📈 25.35 Punkte
🕵️ Sicherheitslücken

🕵️ Medium CVE-2017-18597: Jtrt responsive tables project Jtrt responsive tables


📈 25.35 Punkte
🕵️ Sicherheitslücken

📰 Microsoft Excel Can Now Turn Pictures of Tables Into Actual, Editable Tables


📈 25.35 Punkte
📰 IT Security Nachrichten

matomo