Giter Club home page Giter Club logo

tablesort's Introduction

tablesort

A small & simple sorting component for tables written in JavaScript

Build Status npm version

Quick start

Download the ZIP of this repository or install via command line:

npm i tablesort 
# Or if you're using Yarn 
yarn add tablesort 
<script src='tablesort.min.js'></script>

<!-- Include sort types you need -->
<script src='tablesort.number.js'></script>
<script src='tablesort.date.js'></script>

<script>
  new Tablesort(document.getElementById('table-id'));
</script>

See usage and demos for more


Browser Support

Chrome logo Firefox logo Internet Explorer logo Opera logo Safari logo
8+ ✔ 3.6+ ✔ 10+ ✔ 11.50+ ✔ 5.1+ ✔

Node/Browserify

// npm install tablesort
var tablesort = require('tablesort');

tablesort(el, options);

Default CSS

Add the styling from tablesort.css file to your CSS or roll with your own.

Extending Tablesort

If you require a sort operation that does not exist in the sorts directory, you can add your own.

Tablesort.extend('name', function(item) {

  // Regular expression to test against.
  // `item` is a table value to evaluate.
  return /foo/.test(item);
}, function(a, b) {

  // Custom sort functionality goes here.
  // e.g var n = (a > b) ? -1 : 1;
  return n;
});

If you've made an extend function that others would benefit from pull requests are gladly accepted!

Contributing

Dependencies: Node.js 16 or 18; npm 8.

Tablesort relies on Grunt as its build tool. Simply run npm run build to package code from any contributions you make to src/tablesort.js before submitting pull requests.

Tests are run via:

npm ci && npm t

Licence

MIT

Bugs?

Create an issue

tablesort's People

Contributors

andersos avatar ariarijp avatar asindhu avatar brianlmoon avatar colinodell avatar danieljb avatar davidjb avatar decklin avatar dependabot[bot] avatar dongliu avatar harimohanraj89 avatar jhvst avatar jmlee2k avatar jonashaag avatar kant avatar kausters avatar lunardevelopment avatar matstc avatar omp avatar rogerdodger avatar sabas avatar timbowhite avatar tonglil avatar tripu avatar tristen avatar webgefrickel avatar xpaw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tablesort's Issues

Callback after a table is sorted

Either a callback that can be provided in options, or an event that is triggered for the table element.

I have a lazy load for images, and I want to trigger a check after user sorts the table.

Reverse default sort direction

The default sort direction at the moment is sort-up. That means if you have a numeration it will start with the largest number. I think thats counter intuitive.
What do you think?
I can send you a pull request if you want to.

What IE version should we support?

If we drop support for IE8, we could replace addEvent() function with direct addEventListener call. We could use classList if we went for IE10 support.

Type Error

Hello;
I'm using minified version of your plugin. I get this error

TypeError: e is null ------ tablesort.min.js (line 6)

Please help me to solve this.

Slight refactor

There are many functions that are defined within sortTable, it would be better to move them out, and place them next to test functions. Perhaps some other stuff could be re-ordered as well so there is some kind of structure.

Extending tablesort

Discussion started here: 9a8b294#commitcomment-9804379

Basically, move algorithms like dot separated sorting and file size sorting into separate plugins, and allow extending tablesort. We can do that by either having a new method to register new sorting methods, or provide them in options argument.

Add/Remove from existing th classes instead of completely replacing them

Hey Tristen :),

Following my last week's micro-review, I figured I might aswell fill in an issue for the problem I raised with the th classes being completely replaced by tablesort's ones.

So there you go -> Tabletsort replaces th classes instead of adding/removing to/from them, which breaks the layout on tables that require existing classes to be properly layed out :).

Keep up the good work!

Enhancement: multilevel sorting

I am having a table which has recursive data. What that means is that the table has some sort of grouping labels in certain rows.

For example my table could look like this:
(Just for good measure, my table is a Pivot Table which uses "Brand" as the first label and "Category" as the second label.

Brand | Quantity in stock

  • G-star | 20
    • Pants | 10
    • Shirts | 7
    • Shoes | 3
  • Vans | 7
    • Shirts | 6
    • Shoes | 1

That is the result I would like when sorting on "Quantity in Stock"

When I sort on Brand I would like to have it ordered by Brand, but the name of the brand (in my case) should act as a "parent" of the items in it.

What a solution might be:

Adding some sort of a "Level" integer to the data-level attribute of a < tr >. Maybe this won't work that great, so perhaps a data-parent attribute where you can add the id of the parent. Which is a integer as well. I don't want to use the id attribute for this, since I don't want to use that in this case. I just want to assign an integer if that is possible.

👍 I am working for my company on a system that really needs this plugin. You have made only plugin that works properly (besides of #12 but that doesn't matter). We need your plugin, so I am hoping you are willing to put some extra time in the code. I am not that great in Js, so I can't do it myself. I'm more of a PHP guy :)

Data-sort Not Taking Precedence

I am trying to sort two columns with irregular data. As per the documents, I gave each a data-sort attribute to take precedence over the actual information.

Each time I try to use them however, I am given an error saying that the variable is undefined:

tablesort.min.js:5 Uncaught TypeError: Cannot read property 'match' of undefined

sort

Can't get it to work

Hi all im trying this out for my websites game sales page, but it doesn't seem to want to sort it for me.

Testing it out on the name column, but checking in the inspector gives me this js error:
Uncaught TypeError: Cannot read property 'tagName' of null tablesort.min.js:8Tablesort tablesort.min.js:8(anonymous function) sales_new.php:187

Edit > That error is gone, but no sorting happens.

Sort on initial Tablesort creation?

The table is initially unsorted when it's loaded. Is there a mechanism (or a cute tricky way) to force sorting on an arbitrary column in the 'new Tablesort (...)' call?

I have a list of IP addresses that are built on the fly, but are unordered. When I call 'new Tablesort (...)', I'd like to be able to pass in a default column to sort on.

Undefined error

I am getting "Uncaught TypeError: Cannot read property 'trim' of undefined" in tablesort.min.js:5 when trying to sort and empty table by clicking on the column header.

Issue with sorting numbers

I've tested your library with a table containing numbers. It seems that numbers are sorted as string values rather than actual number values.

E.g. in an array of values [ 3, 27, 31, ... ], the value 3 is placed between 27 and 31 but it should be placed before 27 instead.

Live demo: http://jsfiddle.net/nrm7F/

How do I fix this?

Paginations

Do you will create a pagination tool for this package?

Problem sorting positive and negative values

Hi,

I've implemented your sorting script on a table that has a column with positive and negative values. It is having trouble sorting this column correctly.

I don't have a working table to show because it is an internal tool still in development but i am attaching some screenshots below that illustrate the problem.

It should only have two sorts, ascending and descending, but it seems to sort it 4 different ways. Two different ways for ascending and two different ways for descending. I am attaching one screenshot with the same column shown 4 different times, each corresponds to a mouse click on the same column header.

Do you know what the problem might be here?

Thank you,

Thiago

screenshot

Tabs or Spaces?

What indentation style are we going to be using? tablesort.js uses 2-spaces per indent, while src/sorts/*.js uses a single tab.

(I prefer 2-spaces, but that's just my opinion.)

Tests.

Definitely need to write some and tape is great.

Sort gets stuck in one direction.

I am using backbone to load a collection into a table.

After it loads, THEN I create and call the sort. However, it gets stuck sorting the table in the initial direction, and refuses to sort in the other direction.

If anyone has had experience or tips with this, your information would be highly appreciated.

Sort a date column that has empty cells

When sorting a date column that has some empty cells (or for that matter any cell that doesn't contain a valid date) it screws up the sort since parseDate returns NaN.
I applied a fix locally, don't have the energy now to push a fix so I'm posting it here.

tablesort.date.js : parseDate
change this line:
return new Date(date).getTime();

to this:
return new Date(date).getTime() || 0;

no-sort rows get pushed to the top

I have a table with a final row that shows totals of the preceding rows. When I add no-sort to the final row and then sort the no-sort row is pushed to the top and then it is no longer sorted.

Keyboard accessibility

Currently it's not possible to sort the table using keyboard only. All cells should get a tabindex="0", with enter key handled.

td with img tag only error

I used the following patch to solve it.

239c239,240
<                         str += that.getInnerText(cs[i]);

---
>                         if(cs[i].tagName !== 'IMG') 
>             str += that.getInnerText(cs[i]);

Date Sorting

Hey, first of all: nice plugin!

I want to sort dates, but somehow i can't!? please check my fiddle and tell me how to sort dates properly?

format: dd-mm-yy
link: http://jsfiddle.net/knzo/h8RGk/

thanks in advance!

Text wrap on verbose columns lost after sort.

Hi
Love the functionality of tablesort, but I have an issue with it sorting columns that require wordwrap,

When when a sort is applied to the initial result (beforeSort.png) the table re-formats so that each row is one line high, (afterSort.png) which has the effect of shoving half the table outside the viewing area.

I tried altering the table css, (table-layout: fixed; word-wrap: break-word;) etc, but now the text overwrites itself (withTableLayoutFixed.png)

Is it possible to sort, while preserving multi-line text in a column?

Cheers Ben

aftersort
beforesort
withtablelayoutfixed

TypeError: that.getInnerText is not a function

I get the javascript error "TypeError: that.getInnerText is not a function" in tablesort.js:330 (or "TypeError: b.getInnerText is not a function" in the minified version) when I have a cell with a for an icon in it.

btw. support for dates in format dd.mm.yyyy would be nice.

Euros not detected as a currency

If you have a value like "1.94€", it will fail to sort correctly.

I would also like to define "99 руб." as a number, to sort correctly. Is that possible?

Descending not working properly

The descending doesn't seem to work properly.

I am building my < tbody > via an Ajax call. When the Ajax calls the success callback function, I call the the sort.refresh();. Ascending works fine, but when sorting descending the values scatter around. And not in the default order, but in some random order.

edit

I found the pattern it is sorting by. For instance I have a few integers in the second column. When I sort "sort-up" it will create the following newRows order.

232, 221, 24, 22, 21, 193, 153, 152, 12, 1.

So, it is sorting by the first number of the integer first, then it is looking at the second number. For some reason it works fine when ordering in the "sort-down" configuration. So the newRows.reverse() function (line 172) seems to fix this bug. I have no clue why. You might want to have a look at it?

Have a look at http://i50.tinypic.com/2mzbhpy.jpg

edit

Also, I seem to fix the problem when I order another column first. So for example I have the column "total" and "deleted", I can sort the "total" with "sort-up" when first sorting the "deleted" column. It's getting stranger and stranger :)

Sort doesn't work in FF 16.02, when <td> has a subelement such as <a href>

It throws the following error:

TypeError: this.getInnerText is not a function
[Break On This Error]   
str += this.getInnerText(cs[i]);

It works fine in Chrome & IE 8, which I checked briefly. I am in the process of creating a fix that will traverse the nodes in the cell until it reaches text, then return that text.

Sound good?

Enhancement: turn off / pause sorting

Sometimes you would like to switch the ability to sort the table in runtime. Is it possible to add such functionality? Something like:

sort.disable(); //set all the to no-sort
sort.disable('brand'); // set the containing "brand" to no-sort
sort.enable(); //reverse of the above

And thus stops the sorting and does not sort on sort.refresh because every column has been set to no-sort (in my case). Because it is messing up my table when I have recursive table reloaded by Ajax because it remembers the sorting column. Or add #13, that will solve the problem as well.

script need thead for correct sorting

have:

<table>
    <tr>
        <th>text</th>
        <th>num</th>
    </tr>
    <tr>
        <td>foo</td>
        <td>123</td>
    </tr>
    <tr>
        <td>bar</td>
        <td>159</td>
    </tr>
</table>

browser output:

<table>
    <tbody>
        <tr>
            <th>text</th>
            <th>num</th>
        </tr>
        <tr>
            <td>foo</td>
            <td>123</td>
        </tr>
        <tr>
            <td>bar</td>
            <td>159</td>
        </tr>
    </tbody>
</table>

script need thead for correct sorting (numbers, strings, etc)

Great Plugin - an idea

Hi Tristen,

Great plugin. Would it be possible to optionally just add a class to tables one wants sorted? I.e. just add the class "sortable" and then the scripts finds all tables (keep in mind there can be more than one table on a page) with that class and makes them sortable.

:-)

[Question] Excluding one column

Hey,

is it possible to exclude one column. By excluding I mean if you sort the table that this column stays the same ? Would be very helpful for ranking list where you would like to see the rank for the category.

Currencies with fractions

Hi,

I have a table with values 300€, 300.5€ and 301.22€. For a reason or another, when the table is clicked, the first value is 300.5€, the second is 300€ and the last one is 301.22€. I guess the table is sorted as a string?

Anyway, I took a look at the source code and found that the currency regexes do not take fractions into count. I wonder would you have interest to add that to the library? I personally came up with /^-?\d+\s*([,\.]\d{0,2})?[€]/. Also, if you would want to support values with omitted zero, like .314, you could use /^-?\d*\s*([,\.]\d{0,2})?[€]/.

I aimed my regexes to behave as much the same as the older one.

Let me know if you are interested in implicating either of my versions. I'll follow up with a pull request with changes made to both prefixed and suffixed currencies, plus optionally for the number regex, if you think adding the zero omission is a go.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.