JS:SortedTable

SortedTable is a script that takes a valid table and makes it sortable and also allows you to move rows around. It’s mission is to be the foundation for widgets that do interesting stuff in the new wave of Web 2.0 applications.

Concept

SortedTable is trying to solve a very specific problem – sorting a table automatically (sort functions) or manually (move functions). Anything else is out of the scope and will not make it into the code. The idea of the evolution is to make the code leaner (smaller) but more useful. Any suggestions and contributions are welcome as long as they follow these simple rules. I’m not trying to create a widget. If I ever do it will not change the code of the SortedTable object.

History

0.8

  • first version that actually works on windows and has most of the needed features

0.8a

  • changed the behaviour of sorting:
    • axis=”string” now defaults to case insensitive smartcompare that puts 10 after 9, not after 1
    • no axis does normal compare (broken in 0.8)
    • axis=”sstring” added – does smartcompare case sensitively

0.8b

  • corrected a weird error that broke some sorts in ie6
  • added the possibility for a nonsortable column via class=”nosort” on the th cell
  • added the possibility to ‘regroup’ tbody elements if there’s more than one (for whatever reason)
  • added additional hook to put your custom javascript on (onsort)

0.8c

  • added additional hook to put your custom javascript on (onmove)

0.8d

  • added the option to allow only single line selects
  • corrected compare so that only strings enter compareSmart (error when trying to do split on a DOMElement)
  • changed parseInt to parseFloat for axis=number when sorting
  • changed compare – title now always overrides the value
  • added onselect that happens after onbodyclick

0.8e

  • corrected a bunch of small issues noticed while writing the documentation
    • added return true to selectRange (when it’s actually a range)
    • corrected prepHeader (callbacks on hover were broken)
    • removed redundant s_table variable from prepBody
    • moved onselect to the select method
    • added ondeselect
    • changed parameters to onsort and onmove
  • corrected a few sorting bugs
    • on axis=number NaN is now changed to Infinity to place nonnumeric values at the end
    • in smartcompare numbers go before text
  • corrected an error in the removeBeforeSort code (no nextSibling broke it)
  • added checking in prep so it cannot be done twice
  • added the option to disallow deselect

Future development

The next version will implement a Quicksort algorithm for sorting that will hopefully work a lot faster. It will allow the absence of header and axis properties for each cell that should make the html somewhat smaller.

Download

Check the SortedTable page here or just download the javascript.

Also worth reading

98 Responses to “JS:SortedTable”

  1. ionut says:

    Hi,
    I must say your script is great! One issue though: I can’t make the table rows alternating after I sort it(I have two class=”odd” rows consecutive). Any idea why is that?

  2. abstinent says:

    Hello, Marko, it seems to me that for xml island tables the script still does not works. Something happens, however, the table blinks… but no sorts…
    Can you help me?

  3. Brian says:

    I am playing with the move from table to table portion of the script. The first table (s) needs to be sortable, however, I don’t want table (d) or the second table to sort. How could I accomplish this? I see the sort data in the sortedtable.js. If I remove, both tables become unsortable (I know why). I suppose I need some code to bypass the sorting if indicated. But how? I’m somewhat new to JS, too.

    Thanks for the wonderful script. It’s very very cool!!

    Brian

  4. Steve says:

    My page at http://www.stevelim.com/links/friends_links.html seems to work correctly for firefox, but does not sort in IE.

    Any ideas?

    The data in the tables are php generated and non-static, if that has any bearing on it.

    Thanks,

    Steve.

  5. Steve says:

    I also wanted to add to my post above that the IE error I get is this..

    Line:103
    Char: 3
    Error: ‘this.body’ is null or not an object
    Code: 0

    Thanks,
    Steve.

  6. I’m sorry it took me so long – I’ve been sorting out some personal stuff. I hope it’s not too late and I can help you all now…

    ionut – most probably you don’t have the colorize function attached to the correct events on the SortedTable objects.

    abstinent – can you give me an example? I haven’t worked with XML data islands a lot – I had a case when writing the script and it seemed to work back then. A change in the script might have changed that…

    Brian – ideally what you would do remove the sorted value from the class attribute from the destination table and change the moveRows so that it would only move the selected rows. If you want to use the whole function I would suggest commenting out the line with d.sort(); in it.

    Steve – the first thing to do is get rid of a lot of JavaScript. The script tag you copy-pasted from the examples page should only read:
    <script type=”text/javascript”>//<![CDATA[
    onload = function() {
    mySorted = new SortedTable();
    }
    </script>
    If it still breaks let me know, I don’t see anything wrong with the HTML.

  7. Steve – the last line should of course be:
    //]]></script>

  8. Steve says:

    ego,

    Thanks for replying.

    I replaced the huge script snipped from your example with the following..

    //

    Good news is.. there are no more errors in IE.
    Bad news, it stops sorting (working) completely in all platform/browsers.

    Steve.

  9. Steve says:

    The working code is as follows..

    //

    I was missing the var sourceTable;

    Also worthy of note is that in Samn’s post –

    “If you don’t want the text to appear redundantly as the title, you can make up a property like [a sortdata=”text” href=”url”]text[/a] . The rendering engine will ignore the property “sortdata”.”

    The above works great for FF but not IE. I had to use eg. title=”texthere” for IE to play nice.

    Thanks again,
    Steve.

  10. Steve says:

    Sorry to keep adding comments. But I realized that the hack that Samn posted about sorting hyperlinks does not work completely with IE. Only with FF. Even with bogus attributes or title tags added to fool the sorting.

    If anyone finds a solution, let me know.

    Steve.

  11. Steve says:

    Ok. More digging I have discovered a bug with trying to use hyperlinked text with the sorttable.

    Basically in IE only there is this problem with single word text vs. phrases with spaces (2 or more words). They are not treated or sorted in the same way.

    If you mix hyperlink text of single words with multiple words, IE sort gets ‘confused’. You can test this and see a problem.

    My ugly hack is to add a ‘ .’ at the end of the single word text data for urls.

  12. Mark says:

    I integrated your example table into my application, and it works just fine. However, when I put the table in a backend .php file and then use XMLHttpRequest() to bring in the table, it brings and displays the table just fine, but does not sort. It is just a normal table.

    I’m new to javascript and ajax, and so probably need help where I shouldn’t if I knew better what I was doing. Any ideas?

    Thank you
    Mark

  13. Mark says:

    I solved my own problem. Your onload function I made into a function I call once the data has been loaded.

  14. Mark says:

    I’m continuing to work with this. My ignorance is with DOM. I’ve given the tag an id matching the key in my database. Within the moverows() function, how would I capture the id of the moved rows so that I could then update the database?

  15. Mark says:

    Previous entry unclear. It is the TR tag that has the id=372 or whatever the keyfield of the database is.

  16. Firstly I think that you need to have a letter for the beginning of the id (HTML spec).

    To see what is going on in s move function you can add an event handler (it’s called onmove). It will be called with the same parameters as the move function, so you can easily add database functions.

  17. Mark says:

    Thanks ego for responding. I am moving rows from one table to another, as in the last part of your Examples page. I found the function moverows() in your sample code. Any reason that isn’t in the documentation page yet?

    It is moving rows fine, and I can capture the id of the row I need by looking at the selectedElements I am moving.

    Now, I am working through an error I’m getting in the line :
    // var tds = elm.getElementsByTagName(‘td’);
    even when the code is purely from the example page. It was working, I think. It is saying that line “is not a function”. I’ve eliminated whitespace, having researched and found discussion of the phantom node issue.

  18. Mark says:

    I wish I could edit a post here. Meant to ask “Why isn’t moverows() part of your sortedtable.js”?

  19. Mark says:

    Steve,

    Attempting to chase down a problem I’ve having, I pared your Example page down to the bare essentials to play with Moving Rows from one table to another.

    I’m getting a real oddity. If I change the Destination table’s id from ‘d’ to anything else, the destination table sorts once and quits. I can change the id of the source table with no problems. Email me for sample pages URL if you want. I’m changing the name three places : the new SortedTable(), the CSS, and the id of the table itself.

  20. I’ve only added the moving rows to examples to show that the script works with live data. It’s a thing that doesn’t actually has anything to do with sorting…

  21. Mark says:

    Ego. For some reason, I thought your name was Steve. My question of August 8 regarding changing the name of tables is directed to you. I tried it with your full Example page too. I changed the name of the destination table at the end from “d” and it stops working. – thanks Mark (PS. Can you email me, I have a private question.)

  22. Ronhead says:

    hi
    ive a big problem..

    how i can center rows with numbers?
    i cant do its, i use and

  23. Daniel says:

    Great script!

    I added it to a project with a dynamic table from a database and each time I sort the table, a cookie is updated with the column title and sort direction. The reason is to remain the sorted column when visit the page next time. Works great!

    Just one thing, when using IE6 or 7 with a large number of rows (more than 100) the performance while scrolling in the table with the mouse wheel is very week. It’s the same with the examples if I copy paste a few hundred rows more. But I have no such problem when using FireFox.

    Is it related to the possibility of selecting rows and can I get rid of the selctions because I don’t use it?

  24. Daniel says:

    I guess it wasn’t so difficult after all
    “//this.prepBody();”

  25. Musa says:

    hi
    when you release a new version of sortedtable.
    And i have same problem with Daniel. But i use mouseover function. When i disable this.prepBody(); line said so Daniel, everyhings work fine. But can you fix this problem another way?

  26. secret1029 says:

    Hi, Could this javascript be used with mysql ?

  27. Chris says:

    I have an example table that is currently sorting incorrectly because it is comparing initial whitespace characters to alpha characters–sort by the Notes column and “Inactive” will precede “Crazy”:
    http://osric.com/chris/javascript/sort-table/sort-table.html

    I saw in the documentation that there is a trim(str) helper function, but I’m not sure how to best to hook it in to the rest of the code. Any advice?

    For now I’ve just been more meticulous about keeping extraneous whitespace out of my code (which is probably for the best anyway!) but comparing trimmed strings may be a useful option to include.

  28. Bob says:

    BIG BUG!!!
    If you dynamically delete some row, such problems arose:
    1) In Opera: after sort, deleted rows come back
    2) In IE: after sort, Javascript throws Invalid Pointer exception.
    To correct this in sort function add: this.parseCols():
    if (!elm) return false;
    this.parseCols(); // add this row!!!

  29. Bandzula says:

    I have 2 table on page. Function colorize work only with first table. I need alternate colors on second table too.
    Help please !!

  30. The colorize function is only an example. Ideally you would create a function that would apply it to all the sorted tables – the example code only applies it to a single table.

  31. srinadh says:

    When am using the above sorting function for multiple function and calling the script externally am not able to reverse the order of rows after sorting is done for the first time….

    Help me out…………………

  32. dario says:

    I have tried many sortable table techniques so far.
    But every one, including yours, have a problem with foreign languages special characters. Like čšž.
    Can you please help me with sorting function which can properly recognize these spec. chars?

    Thanx in advance!

  33. The issue is not with the scripts it’s with the way JavaScript internal sort works. You can bypass this with a custom ordering script or by adding a title to the cell where you replace the caron characters with something that will sort properly. One possibility would be to replace č with cz in the title…

    I’ll try to write a sorting function that would be generated by passing it a string that represents the sorting order of specific characters. Don’t think there’s a really fast way of doing it though…

  34. dario says:

    Interesting thing with these characters is they are sorted well but begining at the end of english alphabet, after letter z…

  35. daniel says:

    hello, is it possible to let a column completly unsorted, for example a column with fixed numbers from 1 to x? thanks.

  36. Unfortunately not – the thing is that rows are sorted. You could however attach an event to the sorting that would iterate through the rows and change the number in a cell to whatever you want after the sort.

  37. baxter says:

    Hi Ego
    Very great job!
    I used it with few rows but now I’ve more than 1000 rows, and I’ve the same problem as Daniel. Moreover I use “select” and “move” functions with 2 tables. So I can’t disable “prepBody()”. Selecting and moving action become very slow. I tried to create several “tbody” statements but still slow. Firefox is ok, only IE is affected. Is there something to do, do you have an idea?

    Thank you very much

  38. salvatore says:

    Dear Marko,
    first excuse me for my english.
    I’ve a problem with your script.It doesn’t work when i rebuild the body
    of my table with an ajax calling.
    If i used your script on the static table loaded the first time in the page
    it works very good,but when the tbody of my table is dinamicaly
    rebuild it stop tu work.

    my code:

    #
    Data
    Tipo Doc.
    Numero Documento
    Bollo
    Iva
    Imponibile
    Totale
    Data Rimborso
    Doc. Rimborso
    Ente

    <input type=”radio” name=”doc” id=’doc’ value=” onclick=”selezionaDocumento(this.value)”>
    <input type=”hidden” name=”hdnTipoDocumento” id=’hdnTipoDocumento’ value=” />
    <input type=”hidden” name=”hdnProgressivo” id=’hdnProgressivo’ value=” />

     

     

     

     

     

     

     

     

     

     

  39. @salvatore – if you init the table with var myTable = new SortedTable(tableId); you should do myTable.parseCols(); after you change the table body.

  40. Salvatore says:

    Dear ego,
    i have try to insert this strig (myTable.parseCols();)
    in my code,but it doesn’t work yet.
    Now i’ve debugged my application with firebug,
    an i’ve seen that the order in sorted funcition work only
    with the old rows of the tbody.
    Have you got an idea???.
    Thanks

  41. steve says:

    Hi. Question pls.

    Does this script handle a secondary field sort as well? if so how please?

    Thanks.

  42. Bret says:

    I love this but for one issue that I have not had the time to wade into yet. If a text field begins with inf it will not sort properly. I was able to do this with the example on
    http://www.ajaxdaddy.com/demo-sorted-table.html

    I will let you know if I can figure this out it has to be something funky in the comparator function I assume.

    values used:


    player y
    1.1.1986

    € 881.234,66


    a player
    1.1.1985

    € 881.234,66

    3
    abc player 3
    12.10.1985
    1,7210
    € 1.123.885,17

    4
    main 2
    12.11.1985
    1,5362
    € 772.255,99

    2
    inf 10
    11.10.1985
    1,7353
    € 813.551,04

    1
    henry
    10.11.1985
    1,3013
    € 941.751,75

    5
    jobob 
    13.10.1985
    1,6823
    € 985.123,32

  43. filip says:

    Hello!

    Shift + left click on the same item gives this error:

    Cannot read property ‘previousSibling’ of null
    Cannot read property ‘nextSibling’ of null

    It does so in your example aswell. Got any quick fix for this?
    Thanks!

  44. On OSX shift+click does nothing special – also gives no errors. Please elaborate…

  45. filip says:

    On a windows machine (chrome):

    Clicking on a row in the table selects a row, (row changes colour).

    If I then have no rows selected and I hold in Shift and left click on a row multiple times, (same row), you will get this error in the console windows.

    It’s because the script is looking for a previous and next element. But because I’m shift clicking on the same item over and over again it fails.

    After doing so the shift clicking becomes not stable.
    Did it make more sense now? Sorry for my english.

    Thanks

  46. filip says:

    Forgot to add, shift + click selects multiple rows, (selrow class is added to multiple rows)

  47. Filip says:

    Do you have a solution for this Marko? I would love to use this fantastic script in my new project but the multiple select errors prevents me from using this library :(

Leave a Reply