Ordering a column of select boxes as numbers

Ordering a column of select boxes as numbers

michaelcpaulmichaelcpaul Posts: 2Questions: 1Answers: 0

I'm using a modified custom ordering function from this page:https://datatables.net/examples/plug-ins/dom_sort.html.

I have a column of select boxes that contain either no value or a number. I want to order the values numerically, so I'm using the following function:

 /* Create an array with the values of all the select options in a column, parsed as numbers  */
$.fn.dataTable.ext.order['dom-select-numeric'] = function  ( settings, col ) {
    return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
            if ($.isNumeric($('select', td).val())) {
                    return $('select', td).val() * 1;
            }
            else {
                    return 0;
            }
     } );
}

This works to a degree; the no value case is sorting to the top. However, the numbers are sorting as text like so:

[blank]
10
116
12
9
...

where I want:

[blank]
9
10
12
116
...

Any idea how I can make this work? Thanks in advance!

Answers

  • kthorngrenkthorngren Posts: 21,578Questions: 26Answers: 5,000

    Looks like it is sorting as text not numeric. The natural sorting plugin may help.

    Kevin

  • michaelcpaulmichaelcpaul Posts: 2Questions: 1Answers: 0

    Thanks Kevin; turns out I did need the plugin but you got me looking at that page and I saw that I was missing 'numeric' for the type. I had:

    'columnDefs': [
        {"targets": 15, "orderable": false},
        { "orderDataType": "dom-select-numeric", type: '', "targets": [ 16 ] },       
    ] 
    

    but should have had:

    'columnDefs': [
        {"targets": 15, "orderable": false},
        { "orderDataType": "dom-select-numeric", type: 'numeric', "targets": [ 16 ] },       
    ] 
    
This discussion has been closed.