Datatables sorting varchar

浪子不回头ぞ 提交于 2020-01-06 19:18:51

问题


I have a SQL query that is pulling back results ordered correctly when I try the query in MSSQL Studio.

I am using Datatables from Datatables.net and everything is working great apart from a sorting issue. I have some properties in the first column and I would like to order these like this:

1
1a
1b
2
3
4a
5
etc

However what comes back is something like this:

1
10
100
11
11a

I have looked though various posts but nothing seems to work and I believe that this must be something I should trigger from the datatables plugin but cannot find anything.

Could someone advise?


回答1:


Your data contain numbers and characters, so they will be sorted as string by default. You should write your own plugin for sorting your data type. Have a look at here and here to see how to write a plugin and how to use it with your table.

Edit: got some time today to work with the datatable stuff. If you still need a solution, here you go:

//Sorting plug-in
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
    //pre-processing
    "numchar-pre": function(str){
        var patt = /^([0-9]+)([a-zA-Z]+)$/;    //match data like 1a, 2b, 1ab, 100k etc.
        var matches = patt.exec($.trim(str));
        var number = parseInt(matches[1]);     //extract the number part
        var str = matches[2].toLowerCase();    //extract the "character" part and make it case-insensitive
        var dec = 0;
        for (i=0; i<str.length; i++)
        {
         dec += (str.charCodeAt(i)-96)*Math.pow(26, -(i+1));  //deal with the character as a base-26 number
        }
        return number + dec;       //combine the two parts
    },

    //sort ascending
    "numchar-asc": function(a, b){
        return a-b;
    },

    //sort descending
    "numchar-desc": function(a, b){
        return b-a;
    }
});

//Automatic type detection plug-in  
jQuery.fn.dataTableExt.aTypes.unshift(
   function(sData)
   {
        var patt = /^([0-9]+)([a-zA-Z]+)$/;
        var trimmed = $.trim(sData);
        if (patt.test(trimmed))
        {
            return 'numchar';
        }
        return null;
    }
 );

You can use the automatic type detection function to let the data type automatically detected or you can set the data type for the column

"aoColumns": [{"sType": "numchar"}]



来源:https://stackoverflow.com/questions/15363042/datatables-sorting-varchar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!