simple-datatables

repository·main·Indexed 23 days ago

https://github.com/fiduswriter/simple-datatables

A lightweight, dependency-free, and extendable JavaScript HTML table plugin (version 10.3.0) that provides sorting, filtering, pagination, and searching without requiring jQuery. It supports initialization via DOM elements or CSS3 selectors, CDN integration, and programmatic data loading. Key features include a comprehensive API for DOM and state access, support for colspan in HTML and JSON data, and the ability to dynamically add columns from remote AJAX sources.

Tokens
28.4K
Snippets
68
Records
176
Agent score
82%

What's inside simple-datatables

  1. Getting Started with simple-datatables

    main
    To begin using simple-datatables, you need to follow a workflow of installation, manual setup (if not using a package manager), and initialization. The library provides various advanced features like datetime sorting, dynamic data updates, and remote column sources. Once initialized, you can interact with the table via its Events, Options, Properties, and Methods APIs.
  2. Behavior of searching, sorting, and CSV export with rowspan

    main

    Rowspan cells interact with core DataTable features as follows:

    • Searching: The content of spanned cells is searchable. The content is treated as if it appears in every row it spans.
    • Sorting: When sorting a column containing rowspan cells, the entire group of rows sharing the rowspan cell will move together to maintain the visual relationship.
    • CSV Export: When exporting to CSV, the cell content is automatically duplicated in all affected rows so that the data remains consistent in a flat format.
    • Filtering: Rowspan cells are handled correctly during filtering operations.
  3. Configure advanced search behavior via HTML attributes

    main

    You can implement multiple search fields and control their behavior by adding specific data-* attributes to the <input> elements within your custom template.

    Supported Attributes:

    • data-columns: A JSON array of column indices that the search should operate on (e.g., [1,4]).
    • data-query-separator: Defines the character used to split the search value for individual search items.
    • data-and: When set to "true", changes the search logic from an OR-search to an AND-search.

    Note: The default values for these behaviors can also be configured globally using the searchQuerySeparator and searchAnd options in the datatable configuration.

    Example Custom Search Input: To create a search input that performs an AND-search specifically on columns 1 and 4:

    <input class='${options.classes.input}' placeholder='AND search for columns 1 and 4' type='search' data-and="true" data-columns="[1,4]">
    <input class='${options.classes.input}' placeholder='AND search for columns 1 and 4' type='search' data-and="true" data-columns="[1,4]" >
  4. Important considerations when using colspan

    main

    When implementing colspan, keep the following rules in mind:

    1. Column Count Consistency: The total number of columns in a row (counting the colspan values) must match the number of headings. For example, if you have 5 headings and one cell has colspan="2", that row should contain 4 cells total (1 spanning cell + 3 regular cells).
    2. Cell Data Format: For JSON data, colspan requires the object format: { data: "content", attributes: { colspan: "n" } }.
    3. Mixed Row Formats: You can mix simple arrays (e.g., ["val1", "val2"]) and object-based rows (e.g., { cells: [...] }) within the same data array.
    4. Column Settings: Column settings like sortable, searchable, or hidden are applied to the first column of the span. The subsequent columns covered by the span are treated as internal placeholders.
    5. Searching and Sorting: Cells with colspan remain fully compatible with the library's search and sort features; their content is indexed and used for operations.
  5. Migrate to the data-driven model in version 6.0.x

    main

    Version 6.0.x moved the 'source of truth' from the DOM to the internal data object.

    • Data Access: Access row data via dataTable.data.data and heading data via dataTable.data.headings.
    • Data Types: Non-string data (numbers, booleans) are now preserved in their original format and only converted to strings when rendered in the DOM.
    • Row/Cell Customization: The render method on columns is no longer used for row-level modifications. Use the rowRender configuration option instead.
    • CSS Selectors: All internal class names are now lowercase (e.g., .datatable-wrapper instead of .dataTable-wrapper).
    • Row Index: The dataIndex property on <tr> elements is now data-index and is always a string.
    • API Changes:
      • sortColumn() is removed; use dataTable.column.sort().
      • dataTable.rows.add() is replaced by dataTable.insert({data: [...]}) for multiple rows.
      • dataTable.init() is removed. To change options, either destroy() and recreate the table, or reset dataTable.data and use insert().
  6. Use rowspan in HTML tables

    main

    When initializing a DataTable from an existing HTML table, the library automatically detects and preserves rowspan attributes defined on <th> or <td> elements.

    <table id="myTable">
        <thead
            <tr>
                <th rowspan="2">Department</th>
                <th>Employee</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td rowspan="2">Engineering</td>
                <td>John Doe</td>
            </tr>
            <tr>
                <td>Jane Smith</td>
            </tr>
        </tbody>
    </table>
    
    <script>
        const dataTable = new DataTable("#myTable");
    </script>
  7. Enable datetime sorting via HTML attributes

    main

    To enable datetime parsing and sorting for specific columns, add the data-type="date" attribute to the <th> elements in your <thead>. If the date format is not standard and cannot be sorted easily, you must also provide the data-format attribute using MomentJS format strings.

    Example of setting date types and formats directly in the HTML table structure:

    <table>
        <thead
            <th data-type="date" data-format="DD/MM/YYYY"></th>
            <th data-type="date" data-format="MM/DD/YY"></th>
            ...
        </thead>
    </table>
  8. Import data from a JSON string

    main

    To import data from a JSON string, use the convertJSON function from simple-datatables. Pass an object with a data key containing your JSON string to convertJSON, then pass the resulting object to datatable.insert().

    import {
      DataTable,
      convertJSON
    } from "simple-datatables"
    
    const dataTable = new DataTable("#myTable")
    const convertedData = convertJSON({
      data: // the JSON string
    })
    dataTable.insert(convertedData)
  9. Use simple-datatables via CDN

    main

    To use the library without a build step, include the CSS and JavaScript from a CDN in your HTML.

    Important: For production environments, it is highly recommended to pin the version to a specific major or minor version (e.g., @6 or @6.0) to prevent breaking changes from accidental updates.

    <link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" type="text/css">
    <script src="https://cdn.jsdelivr.net/npm/simple-datatables@latest" type="text/javascript"></script>
  10. Update layout and class names for version 7.0.x

    main

    Version 7.0.x introduced several breaking changes to configuration and styling:

    • Layout: The layout option was replaced by the template option. You should use the template configuration to define the placement of table elements.
    • Class Names: Default class names were updated to include the datatable- prefix:
      • active $\rightarrow$ datatable-active
      • asc $\rightarrow$ datatable-ascending
      • desc $\rightarrow$ datatable-descending
      • disabled $\rightarrow$ datatable-disabled
      • ellipsis $\rightarrow$ datatable-ellipsis
    • Column Types: The type option in columns now supports html (renders tags), string (escapes tags), date, number, boolean, and other.
    • Column Styling: Use headerClass and cellClass within the columns option to specify classes for header or body cells.
    • Data Conversion: The dataConvert option was removed. Instead, manipulate datatable.data.data directly and call datatable.update().
  11. Import data from a CSV string

    main

    To import data from a CSV string, use the convertCSV function (note: the documentation example uses convertJSON for the CSV logic, but refers to convertCSV in the import). Pass an object to the converter with the following options:

    • data: The CSV string.
    • headings: Boolean indicating if the first row contains headings.
    • columnDelimiter: The character separating columns (e.g., ",").
    • lineDelimiter: The character separating rows (e.g., "\n").

    Then, pass the converted data to datatable.insert().

    import {
      DataTable,
      convertCSV
    } from "simple-datatables"
    
    const dataTable = new DataTable("#myTable")
    const convertedData = convertCSV({
      data: // the CSV string,
      headings: true,
      columnDelimiter: ",",
      lineDelimiter: "\n"
    })
    datatable.insert(convertedData)
  12. Use colspan in table headings

    main

    You can create grouped column headers by applying the colspan attribute to objects within the headings array of your data configuration.

    const data = {
        headings: [
            "Product",
            {
                data: "Q1 Sales",
                attributes: {
                    colspan: "3"  // Groups 3 months
                }
            },
            {
                data: "Q2 Sales",
                attributes: {
                    colspan: "3"  // Groups 3 months
                }
            }
        ],
        data: [
            [
                "Widget A",
                "Jan: $1000",
                "Feb: $1200",
                "Mar: $1500",
                "Apr: $1300",
                "May: $1400",
                "Jun: $1600"
            ]
        ]
    };
    
    const dataTable = new DataTable("#myTable", {
        data: data
    });