Jump to content

MediaWiki:Common.js

From Carbon Accounting Alliance Wiki
Revision as of 21:03, 11 March 2025 by WikiSysop (talk | contribs)

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/* Any JavaScript here will be loaded for all users on every page load. */

#Filterable tables
mw.loader.using(['jquery'], function () {
    $(document).ready(function () {
        function addFiltersToTable(table) {
            var thead = $(table).find("thead");
            if (thead.length === 0) {
                // If no thead exists, create one from the first row
                var firstRow = $(table).find("tr:first");
                thead = $("<thead></thead>").append(firstRow.clone());
                $(table).prepend(thead);
            }

            var headerRow = thead.find("tr:first");
            var filterRow = $("<tr></tr>");

            headerRow.find("th").each(function (colIndex) {
                var filterCell = $("<th></th>");
                var input = $("<input>").attr({
                    "type": "text",
                    "placeholder": "Filter...",
                    "class": "table-filter"
                });

                input.on("keyup", function () {
                    var filterText = $(this).val().toLowerCase();
                    $(table).find("tbody tr").each(function () {
                        var cellText = $(this).find("td").eq(colIndex).text().toLowerCase();
                        $(this).toggle(cellText.indexOf(filterText) > -1);
                    });
                });

                filterCell.append(input);
                filterRow.append(filterCell);
            });

            thead.append(filterRow);
        }

        // Apply to all tables with class 'filterable-table'
        $("table.filterable-table").each(function () {
            addFiltersToTable(this);
        });
    });
});