Custom sorting on a column within "render" (multiple numbers)

Custom sorting on a column within "render" (multiple numbers)

s427s427 Posts: 6Questions: 3Answers: 0

I have a table that uses dataTables in AJAX mode. One of the columns contains one or two numbers (float). If there are two numbers, they are separated by a semi-colon. Example: 65.00;67.00

I want my users to be able to sort this column numerically, with this simple rule: if there are two numbers in a cell, dataTable should just ignore the second one. So in the example given above, just use 65.00 as a sorting value.

I'm trying to do that using the "render" option in columnDefs, but although the function is indeed triggered when I sort my column, the result is still sorted alphabetically (with "100" before "12", for instance).

Here's the part of columnDefs related to this column:

{
    "targets": 8, // using an array as source
    "render": {
        "display": function (data, type, row, meta) {
            if (data) {
                var r = '';
                var temp = data.split(';');
                if (temp[0]) {
                    r = temp[0];
                    if (temp[1] && temp[1] != temp[0]) {
                        r += '-' + temp[1];
                    }
                }
                return r;
            }
        },
        "sort": function (data, type, row, meta) {
            var r = 0;
            if (data) {
                console.log('sort:', data, '->', parseFloat(data));
                r = parseFloat(data);
            }
            return r;
        },
    },
},

When I trigger the sort (by clicking on the column header), the console.log is indeed printed to the console. Yet the resulting sort is still alphabetical.

What am I missing?

Answers

  • kthorngrenkthorngren Posts: 21,173Questions: 26Answers: 4,923

    Yet the resulting sort is still alphabetical.

    Datatables type detection is detecting the column as a string not a number. Try changing your columns.render function to this structure:

    "render": function ( data, type, row, meta ) {
        if ( type === 'sort' || type === 'type' ) {
            return data.split(';')[0];
       }
       if ( type === 'display' ) {
           // Manipulate your display data 
          return r;
       }
       return data;
    }
    

    Adjust the code as necessary but, if return data.split(';')[0]; returns a numeric value, the column will be set to number and sort appropriately.

    If you still need help with this please build a simple test case that we can work with.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • s427s427 Posts: 6Questions: 3Answers: 0

    I'll try that, thanks!

This discussion has been closed.