Handling custom sorting in a dynamically generated table (variable column count)

Handling custom sorting in a dynamically generated table (variable column count)

a.quackenbosa.quackenbos Posts: 4Questions: 0Answers: 0
edited August 2009 in General
I'm not exactly a javascript master, so I figure this is the best place to ask about this. I'm generating a table with PHP that has a variable amount of data in it - the column count could change based on the parameters set by the user, and the types of data in the columns is also variable - some string, some floats, some regular numbers. None of the columns holding currency or percents are sorting right, obviously due to the $ and % symbols.

Considering that I have no real way of telling which columns will hold what (without a very brute-force-ish algorithm, which is what I'm trying to avoid), is there a way to handle this cleanly? Perhaps a way to dynamically detect types and assign a different sorting function to said columns?

Replies

  • allanallan Posts: 61,726Questions: 1Answers: 10,109 Site admin
    Hi,

    There most certainly is a way to do this - it's DataTables type detection plug-in :-) Have a look at this page: http://datatables.net/plug-ins#type - there is even a plug-in which should do the trick for you perfectly! Use this in combination with the currency sorting plug-in and that's that!

    Demo: http://datatables.net/examples/example_sorting_plugin.html

    Regards,
    Allan
  • a.quackenbosa.quackenbos Posts: 4Questions: 0Answers: 0
    Thanks, this does look like it will help. However, I'm also having an issue with normal integers not being sorted properly (they're being sorted on a string-type basis it seems: list of numbers sorted as 3, 35, 4, 40, 450, 5, etc in that order). Is the type not being picked up, or do I need to enforce the numeric typing somehow? I know there's a section in the examples on assigning each column a type, but with my columns being generated dynamically I'm not sure how to handle this.
  • allanallan Posts: 61,726Questions: 1Answers: 10,109 Site admin
    Hi,

    If they are being sorted as strings, then DataTables must be picking up some non-numeric character somewhere in that column - white space for example can cause this issue. If you make sure that there is only numeric information in the column, there should be no problem with it sorting correctly :-)

    Regards,
    Allan
This discussion has been closed.