A stupidly small and simple jQuery table sorter plugin

Overview

Stupid jQuery Table Sort

This is a stupid jQuery table sorting plugin. Nothing fancy, nothing really impressive. Overall, stupidly simple. Requires jQuery 1.7 or newer.

View the demo here

See the examples directory.

Installation via npm

$ npm i stupid-table-plugin

Installation via Bower

$ bower install jquery-stupid-table

Example Usage

The JS:

$("table").stupidtable();

The HTML:

<table>
  <thead>
    <tr>
      <th data-sort="int">int</th>
      <th data-sort="float">float</th>
      <th data-sort="string">string</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>15</td>
      <td>-.18</td>
      <td>banana</td>
    </tr>
    ...
    ...
    ...

The thead and tbody tags must be used.

Add a data-sort attribute of "DATATYPE" to the th elements to make them sortable by that data type. If you don't want that column to be sortable, just omit the data-sort attribute.

Predefined data types

Our aim is to keep this plugin as lightweight as possible. Consequently, the only predefined datatypes that you can pass to the th elements are

  • int
  • float
  • string (case-sensitive)
  • string-ins (case-insensitive)

These data types will be sufficient for many simple tables. However, if you need different data types for sorting, you can easily create your own!

Data with multiple representations/predefined order

Stupid Table lets you sort a column by computer friendly values while displaying human friendly values via the data-sort-value attribute on a td element. For example, to sort timestamps (computer friendly) but display pretty formated dates (human friendly)

<table>
  <thead>
    <tr>
      <th data-sort="string">Name</th>
      <th data-sort="int">Birthday</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Joe McCullough</td>
      <td data-sort-value="672537600">April 25, 1991</td>
    </tr>
    <tr>
      <td>Clint Dempsey</td>
      <td data-sort-value="416016000">March 9, 1983</td>
    </tr>
    ...
    ...
    ...

In this example, Stupid Table will sort the Birthday column by the timestamps provided in the data-sort-value attributes of the corresponding tds. Since timestamps are integers, and that's what we're sorting the column by, we specify the Birthday column as an int column in the data-sort value of the column header.

Default sorting direction

By default, columns will sort ascending. You can specify a column to sort "asc" or "desc" first.

<table>
  <thead>
    <tr>
        <th data-sort="float" data-sort-default="desc">float</th>
        ...
    </tr>
  </thead>
</table>

Sorting a column on load

If you want a specific column to be sorted immediately after $table.stupidtable() is called, you can provide a data-sort-onload=yes attribute.

<table>
  <thead>
    <tr>
        <th data-sort="float" data-sort-onload=yes>float</th>
        ...
    </tr>
  </thead>
</table>

Multicolumn sorting

A multicolumn sort allows you to define secondary columns to sort by in the event of a tie with two elements in the sorted column. See examples/multicolumn-sort.html. Specify a comma-separated list of th identifiers in a data-sort-multicolumn attribute on a <th> element. An identifier can be an integer (which represents the index of the th element of the multicolumn target) or a string (which represents the id of the th element of the multicolumn target).

Sorting a column programatically

After you have called $("#mytable").stupidtable(), if you wish to sort a column without requiring the user to click on it, select the column th and call

var $table = $("#mytable").stupidtable();
var $th_to_sort = $table.find("thead th").eq(0);
$th_to_sort.stupidsort();

// You can also force a direction.
$th_to_sort.stupidsort('asc');
$th_to_sort.stupidsort('desc');

Updating a table cell's value

If you wish for Stupid Table to respond to changes in the table cell values, you must explicitely inform Stupid Table to update its cache with the new values. If you update the table display/sort values without using this mechanism, your newly updated table will not sort correctly!

/*
 * Suppose $age_td is some td in a table under a column specified as an int
 * column. stupidtable() must already be called for this table.
 */
$age_td.updateSortVal(23);

Note that this only changes the internal sort value (whether you specified a data-sort-value or not). Use the standard jQuery .text() / .html() methods if you wish to change the display values.

Callbacks

To execute a callback function after a table column has been sorted, you can bind on aftertablesort.

var table = $("table").stupidtable();
table.bind('aftertablesort', function (event, data) {
    // data.column - the index of the column sorted after a click
    // data.direction - the sorting direction (either asc or desc)
    // data.$th - the th element (in jQuery wrapper)
    // $(this) - this table object

    console.log("The sorting direction: " + data.direction);
    console.log("The column index: " + data.column);
});

Similarly, to execute a callback before a table column has been sorted, you can bind on beforetablesort.

See the complex_example.html file.

Creating your own data types

Sometimes you don't have control over the HTML produced by the backend. In the event you need to sort complex data without a data-sort-value attribute, you can create your own data type. Creating your own data type for sorting purposes is easy as long as you are comfortable using custom functions for sorting. Consult Mozilla's Docs if you're not.

Let's create an alphanum datatype for a User ID that takes strings in the form "D10", "A40", and sorts the column based on the numbers in the string.

<thead>
  <tr>
    <th data-sort="string">Name</th>
    <th data-sort="int">Age</th>
    <th data-sort="alphanum">UserID</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>Joseph McCullough</td>
    <td>20</td>
    <td>D10</td>
  </tr>
  <tr>
    <td>Justin Edwards</td>
    <td>29</td>
    <td>A40</td>
  </tr>
  ...
  ...
  ...

Now we need to specify how the alphanum type will be sorted. To do that, we do the following:

$("table").stupidtable({
  "alphanum":function(a,b){

    var pattern = "^[A-Z](\\d+)$";
    var re = new RegExp(pattern);

    var aNum = re.exec(a).slice(1);
    var bNum = re.exec(b).slice(1);

    return parseInt(aNum,10) - parseInt(bNum,10);
  }
});

This extracts the integers from the cell and compares them in the style that sort functions use.

StupidTable Settings

As of 1.1.0 settings have been introduced. Settings are defined like so:

var $table = $("#mytable");
$table.stupidtable_settings({
    // Settings for this table specified here
});
$table.stupidtable();

Listed below are the available settings.

will_manually_build_table

(Introduced in verison 1.1.1)

Options:

  • true
  • false (default)

By default, every time a column is sorted, stupidtable reads the DOM to extract all the values from the table. For tables that will not change or for very large tables, this behavior may be suboptimal. To modify this behavior, set the will_manually_build_table setting to true. However, you will be responsible for informing stupidtable that the table has been modified by calling $table.stupidtable_build().

var $table = $("#mytable");
$table.stupidtable_settings({
    will_manually_build_table: true
});
$table.stupidtable();

// Make some modification to the table, such as deleting a row
...
...

// Since will_manually_build_table is true, we must build the table in order
// for future sorts to properly handle our modifications.
$table.stupidtable_build();

should_redraw

(Introduced in verison 1.1.0)

The should_redraw setting allows you to specify a function that determines whether or not the table should be redrawn after it has been internally sorted.

The should_redraw function takes a sort_info object as an argument. The object keys available are:

  • column - An array representing the sorted column. Each element of the array is of the form [sort_val, $tr, index]
  • sort_dir - "asc" or "desc"
  • $th - The jquery object of the <th> element that was clicked
  • th_index - The index of the <th> element that was cliked
  • $table - The jquery object of the <table> that contains the <th> that was clicked
  • datatype - The datatype of the column
  • compare_fn - The sort/compare function associated with the <th> clicked.

Example: If you want to prevent stupidtable from redrawing the table if the column sorted has all identical values, you would do the following:

var $table = $("#mytable");
$table.stupidtable_settings({
    should_redraw: function(sort_info){
      var sorted_column = sort_info.column;
      var first_val = sorted_column[0];
      var last_val = sorted_column[sorted_column.length - 1][0];

      // If first and last element of the sorted column are the same, we
      // can assume all elements are the same.
      return sort_info.compare_fn(first_val, last_val) !== 0;
    }
});
$table.stupidtable();

License

The Stupid jQuery Plugin is licensed under the MIT license. See the LICENSE file for full details.

Tests

Visit tests/test.html in your browser to run the QUnit tests.

int float string
1 10.0 a
1 10.0 a
Comments
  • Don't sort a column with same values

    Don't sort a column with same values

    for a column whom all its values are the same, do not bother sorting. Touching the DOM for no reason costs in performance and if better to avoid.

    Here's a quick idea how to check if all columns values are the same:

    var table = document.querySelector('table'),
        rowsCount = table.rows.length,
        values = {};
    
    
    // lets say a user is sorting the first column
    // skip the first tr which only has "th"..
    while( rowsCount-- > 1){
      values[ table.rows[rowsCount].children[0].textContent ] = 1;
    }
    
    // same value if the object has less than 2 keys
    if( Object.keys(values).length < 2 )
       return; // do not sort
    
    opened by yairEO 19
  • Feature request: a way to sort empty values to the bottom always

    Feature request: a way to sort empty values to the bottom always

    Feature request: a way to sort empty values to the bottom

    For example, when sorting by integers:

    1 a f 6 b 5 c d 3 e

    sorted becomes: 1 a 3 e 5 c 6 b f d

    and sorted again becomes:

    6 b 5 c 3 e 1 a f d

    Would be a useful optional parameter for dealing with optional table columns.

    enhancement 
    opened by pickhardt 15
  • weird behavior when td have empty values

    weird behavior when td have empty values

    Hi,

    I have a table where some tr have empty td, when sorting as int or float, can we put a default value of 0 instead of NaN in Javascript?

    Change this

    "float": function(a, b) {
      return parseFloat(a) - parseFloat(b);
    },
    

    into this

    "float": function(a, b) {
      return (parseFloat(a)||0) - (parseFloat(b)||0);
    },
    

    Empty td will fuck up normal number td sorting. Because NaN - 1 ==== NaN in Javascript. But in table sorting it's better if we think 1 is greater than NaN

    opened by est 13
  • Optimized sorting (when using data-sort-value attributes)

    Optimized sorting (when using data-sort-value attributes)

    Sorting itself was fast but the for/while loops in sort_map() were slow. I found it faster to group sort data + TR references into a tuple, sort the tuple array and then use the TR reference to append the rows back.

    opened by jacobzed 10
  • Recent changes/improvements on my fork

    Recent changes/improvements on my fork

    I have made several changes to my fork of stupid-tables and attempted 2 methods of implementing #54. I'll run through the changes here, and whenever you get the chance to take a look (no rush, I know you're busy) I'd appreciate your thoughts.

    I first created a branch issue54 then later split that off to sortdesc. (The links show the list of commits for each, the diffs should be fairly simple.)


    Extracted sortDir strings to an enum structure Instead of passing strings around, I set up an "enum" to hold them. Unfortunately, creating an object that's accessible to both the plugin and outside code means the best way I could find was $.fn.stupidtable.dir. A little ugly but that can of course be stored in a var for later use.


    Removed unnecessary "is sorted" check The is_sorted_array function didn't seem to save any processing. To check if the array was sorted, it sorts a copy of the array, reverses a copy of that array, then compares both to the original. But then it either reverses the original array again or sorts it again. Now that we have the sort-dir data attribute it's much simpler to just sort the array once, in the required direction.


    New method of forcing redraw Apparently simply reading any style property from an element forces a redraw, so I do that after running beforetablesort. Fixes #53.


    Added 'beforesortmapcreate' callback for modifying the sort-map (issue54 branch) I looked into the sortmap callback that you suggested. To be honest I probably misunderstood what you were suggesting, or else this is gonna overcomplicate things. The plugin change was just one line with the callback, but actually modifying the sort map array (see complex_example.html) turned out to be quite complex. You need to modify the variable in-place due to the way Javascript handles pass-by-reference, plus it requires an extra pass of the array. If you can explain in a bit more detail how you expected this feature to work I can take another crack at it.


    Allow separate sorting function when sorting descending (sortdesc branch) One of the ideas I suggested, and I quite like it personally :) It checks for the existence of a data-sort-desc attribute and uses that as the sorting function instead of the one from data-sort. It's quite flexible as it allows for basically any custom handling, including keeping blank (or specific) rows at the bottom.

    opened by svivian 9
  • Several changes

    Several changes

    The plugin is now chainable. You can use $('table').stupidtable().bind('aftertablesort', function () {// Your custom handler});

    Updated the code to allow nested tables. Previously it was causing the browser to crash.

    Added aftertablesort event

    Used data-sort attribute for enabling sorting and for setting sort type. Also renamed data-order-by attribute to data-sort-value.

    opened by JoyceBabu 9
  • TypeError undefined is not a function

    TypeError undefined is not a function

    I keep getting this error:

    Uncaught TypeError: undefined is not a function jquery.stupidTable.min.js:26

    (anonymous function) jquery.stupidTable.min.js:26
    (anonymous function)
    

    The method in question is:

    h.sort(function(a, b) {
        return m(a[0], b[0])
    });
    
    opened by valtido 8
  • Script too slow warning messages

    Script too slow warning messages

    Hi Guys,

    I got a table of ~2000 records, when I try to sort, there is a small delay (1 or 2seconds) on chrome,

    However on Firefox, this gives a native pop up saying the script is too slow, and wants to continue, stop it...

    I am using a table of 10 columns and 1879 table rows....(if you are going to test this, maybe try a few thousand records to make it work that much harder.

    Is there anything I can do to optimise this?

    if you have any questions do let me know I will try and answer...

    opened by valtido 8
  • Allow user to specify a default sort order

    Allow user to specify a default sort order

    We needed the ability to have the first click on a column header sort descending, rather than ascending. We found it wasn't possible with the library as it was, so we made a little patch that allows the user to supply a new data attribute, data-default-sort. If that is not supplied, it works just as it used to, sorting by ascending on the first click.

    We didn't add any docs or re-minify this version, FYI.

    opened by zephyr-dev 8
  • Add a more obvious/semantic way to trigger a sort without clicking

    Add a more obvious/semantic way to trigger a sort without clicking

    Currently to sort a column without actually clicking, you just simulate a click.

    $("#mytable").find("th").eq(0).click();
    

    Perhaps we should create an alias to the above command, something like

    $("#mytable").stupidsort(0)
    
    enhancement 
    opened by joequery 8
  • Uppercase and Lowercase treated differently

    Uppercase and Lowercase treated differently

    I had some test sample data that was sorting erratically. Had many strings that were "fail" (purposefully), and other strings as well. The thing is, only "fail" sample data was in lowercase, and they were always blocked together away from other strings, but not in true alphabetical order. I can override this with a simple strtoupper() for my data-sort-value. Just thought I'd post this in case it was an issue elsewhere. Here is some sample output without stringtoupper() in place:

    Date Name Price 01/15/2013 2013 Membership $100.00 01/15/2013 2013 Membership $100.00 01/15/2013 2013 Membership $1.00 01/17/2013 2014 Membership $999.00 01/10/2013 A Test $250 01/22/2013 Event Registration Test $10.00 01/10/2013 Fail $1 01/10/2013 Fail $1 01/10/2013 Fail $1 01/10/2013 Fail $1 01/31/2013 THis IS A TEST $125 01/10/2013 The first one $1551 01/10/2013 The first one $1251 01/18/2020 The future payment of the future $10000000 01/10/2013 fail $666 01/10/2013 fail $123 01/10/2013 fail $1 01/10/2013 fail $1 01/10/2013 fail $1

    opened by GhostToast 8
  • get th index from row instead of table

    get th index from row instead of table

    Currently, the sort does not work correctly if you have multiple rows of th's combined with multicolumn-sort.

    If you open this jsfiddle and sort the table by "arms right" multiple times you see that there are 4 different orders. (e.g. once the desc order is Person 3, 6, 5, 4, 2, 1 and another time it is Person 3, 1, 2, 4, 5, 6)

    This happens because the get_th method returns the current th index of the whole table instead of the index of the current row.

    I also created a jsfiddle with the stupidtable including my PR.

    opened by sl-ffx 0
  • Bump lodash from 4.17.15 to 4.17.21

    Bump lodash from 4.17.15 to 4.17.21

    Bumps lodash from 4.17.15 to 4.17.21.

    Commits
    • f299b52 Bump to v4.17.21
    • c4847eb Improve performance of toNumber, trim and trimEnd on large input strings
    • 3469357 Prevent command injection through _.template's variable option
    • ded9bc6 Bump to v4.17.20.
    • 63150ef Documentation fixes.
    • 00f0f62 test.js: Remove trailing comma.
    • 846e434 Temporarily use a custom fork of lodash-cli.
    • 5d046f3 Re-enable Travis tests on 4.17 branch.
    • aa816b3 Remove /npm-package.
    • d7fbc52 Bump to v4.17.19
    • Additional commits viewable in compare view
    Maintainer changes

    This version was pushed to npm by bnjmnt4n, a new releaser for lodash since your current version.


    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • possible to specify an element trigger sorting other than default TH?

    possible to specify an element trigger sorting other than default TH?

    This is probably something exceedingly simple, but I'd like to trigger sorting on click of the title of the <th> only (maybe wrapped in a span?), as I have a second, more granular filtering mechanism in each <th> as well, and I don't want to sort when a user clicks on the icon that triggers my second filtering popup.

    As written, the script sorts on-click anywhere within the <th>, and I'd like to prevent that from happening when clicking on the blue icon within the <th> below:

    Untitled

    And because the icon and dropdown are children of the <th>, clicking on anything inside the dropdown also sorts the table. I've tried using .not() with no success.

    opened by capturedghosts 0
  • Allow th tags in tbody

    Allow th tags in tbody

    Previously, a th tag inside a tbody > tr would cause issues with sort.

    This is bad! We want to encourage <th scope="row"> in our markup. :)

    This 1-line commit fixes that, and updates tests to match.

    opened by skipchris 1
  • Problems with data-sort-value

    Problems with data-sort-value

    Hello, I have a problem with the data-sort-value... I follow the instructions but doesn't sort by data-sort-value but by int (of the td): image How can I fix this? Thanks :)

    opened by LythandeDc 0
Owner
Joseph McCullough
Joseph McCullough
jQuery plugin to show a tree structure in a table

jQuery treetable jQuery treetable is a plugin for jQuery, the 'Write Less, Do More, JavaScript Library'. With this plugin you can display a tree in an

Ludo van den Boom 734 Nov 14, 2022
jQuery plugin for stacking tables on small screens

stacktable.js The Responsive Tables jQuery plugin for stacking tables on small screens. The purpose of stacktable.js is to give you an easy way of con

John Polacek 1k Nov 30, 2022
el-table awlays show horizontal-scroller on bottom

el-table awlays show horizontal-scroller on bottom

Edward Mizuka 24 Dec 1, 2022
A JQuery plugin to create AJAX based CRUD tables.

What is jTable http://www.jtable.org jTable is a jQuery plugin used to create AJAX based CRUD tables without coding HTML or Javascript. It has several

Volosoft 1.1k Dec 21, 2022
Live searching/filtering for HTML tables in a jQuery plugin

jQuery Filter Table Plugin This plugin will add a search filter to tables. When typing in the filter, any rows that do not contain the filter will be

Sunny Walker 175 Oct 29, 2022
jQuery plugin to make HTML tables responsive

FooTable V3 This is a complete re-write of the plugin. There is no upgrade path from V2 to V3 at present as the options and the way the code is writte

FooPlugins 2.1k Dec 19, 2022
jQuery grid plugin

jqGrid jQuery grid plugin jqGrid is an Ajax-enabled JavaScript control that provides solutions for representing and manipulating tabular data on the w

Tony Tomov 2.8k Jan 7, 2023
Lightweight Grid jQuery Plugin

jsGrid Lightweight Grid jQuery Plugin Project site js-grid.com jsGrid is a lightweight client-side data grid control based on jQuery. It supports basi

Artem Tabalin 1.5k Dec 31, 2022
An Obsidian plugin to provide an editor for Markdown tables

An Obsidian plugin to provide an editor for Markdown tables. It can open CSV data and data from Microsoft Excel, Google Sheets, Apple Numbers and LibreOffice Calc as Markdown tables from Obsidian Markdown editor.

Ganessh Kumar 112 Dec 31, 2022
A simple, modern and interactive datatable library for the web

Frappe DataTable A modern datatable library for the web Introduction Frappe DataTable is a simple, modern and interactive datatable library for displa

Frappe 836 Dec 24, 2022
Luckysheet is an online spreadsheet like excel that is powerful, simple to configure, and completely open source.

English| 简体中文 Introduction ?? Luckysheet is an online spreadsheet like excel that is powerful, simple to configure, and completely open source. Links

mengshukeji 12.7k Dec 31, 2022
JavaScript data grid with a spreadsheet look & feel. Works for React, Angular, and Vue. Supported by the Handsontable team ⚡

Handsontable is a JavaScript component that combines data grid features with spreadsheet-like UX. It provides data binding, data validation, filtering

Handsontable 17.4k Dec 28, 2022
Nice, sleek and intuitive. A grid control especially designed for bootstrap.

jQuery Bootgrid Plugin Nice, sleek and intuitive. A grid control especially designed for bootstrap. Getting Started jQuery Bootgrid is a UI component

Rafael Staib 976 Dec 16, 2022
Shrinks any large data tables into compact and responsive tables

jquery.table-shrinker A Jquery plugin to make HTML Table responsive across all devices, the right way! Demo Click here to see the demo, remember to re

null 29 Sep 11, 2022
✏️ A small jQuery extension to turn a static HTML table into an editable one. For quickly populating a small table with JSON data, letting the user modify it with validation, and then getting JSON data back out.

jquery-editable-table A small jQuery extension to turn an HTML table editable for fast data entry and validation Demo ?? https://jsfiddle.net/torrobin

Tor 7 Jul 31, 2022
Mamera is a stupidly silly app developed to test CapacitorJS. It can be found on the iOS App Store.

Mamera This repo is focused on mobile app development for iOS. Although you may be able to build to Android from this repo, this ReadMe was written fo

Jamel 7 Mar 30, 2022
Another table select prompt plugin of inquirer.js, with powerful table render and filters.

inquirer-table-select-prompt Table row selection prompt for Inquirer.js 动机 现有的 inquirer.js 没有支持表格行选中的命令行交互的插件. 社区内能查找到的,只有一个二维数组的 checkbox,eduardobouc

锂电 3 Jan 7, 2023
JQuery-TableToExcel - Light weight jQuery plugin for export HTML table to excel file

tableToExcel Light weight jQuery plugin for export table to excel file Demos Website and demo here: http://tanvirpro.com/all_project/jQueryTableToExce

Tanvir Sarker 4 May 8, 2022
Source code for my tutorial on how to build customizable table component with React Table and Tailwind CSS.

React Table + Tailwind CSS = ❤️ Source code for my tutorial on how to build customizable table component with React Table and Tailwind CSS. Both parts

Samuel Liedtke 147 Jan 7, 2023