lg22woo
lg22woo

Reputation: 106

Explicit Sorting for datatables

I have a column in my datatable that contains status information (i.e. very good, good, ok, bad, very bad), and I'd like to sort by status, not alphabetically. How do I do that?

I just made up this property, but is there something like this?

$("#myTable").DataTable({
    "sortArray": ['very good', 'good', 'ok', 'bad', 'very bad']
});

I did look through the datatables documentation and found custom sorting, but it uses types such as alphabetic and numeric, as far as I can tell.

EDIT: I can't use HTML5 because this must be compatible with IE9.

Upvotes: 0

Views: 181

Answers (2)

Gyrocode.com
Gyrocode.com

Reputation: 58930

SOLUTION 1

You can use columnDefs to target a specific column using zero-based index in targets option and columnDefs.render to return numerical value during sorting (type === 'sort'). jQuery helper method $.inArray() is used to return array index based on the value provided.

$('#myTable').dataTable( {
    "columnDefs": [
        {
            "targets": 0,
            "render": function ( data, type, row, meta ) {
                if(type === 'sort'){
                   var values = ['very good', 'good', 'ok', 'bad', 'very bad'];
                   data = $.inArray(data, values);
                }

                return data;
            }
        }
    ]
} );

SOLUTION 2

Alternative solution is to use data- attributes as shown in HTML5 data-* attributes example.

If you have static HTML data, you could create your rows as shown below, then jQuery DataTables picks up data- attributes and uses them for searching.

<tr>
    <td>T. Nixon</td>
    <td>System Architect</td>
    <td data-order="1">very good</td>
</tr>
<tr>
    <td>T. Nixon</td>
    <td>System Architect</td>
    <td data-order="2">good</td>
</tr>

Upvotes: 1

mauricius
mauricius

Reputation: 116

You could assign a numeric value to each of your statuses (i.e. 1 -> very good, 2 -> good, and so on) and then use the column rendering capabilities of DataTables to map back your numeric value to a text status.

DataTables Column rendering

Upvotes: 0

Related Questions