1
votes

I am following this DataTables example to add sorting on columns with an input field: http://datatables.net/examples/plug-ins/dom_sort.html

In my code below, the second targeted column (6), is a numeric field, and sorts fine, however the first column (5), a text column, doesn't sort at all. Using Chrome developer tools I can see it stepping into the function, but no sorting takes place. Both columns are input fields. I am using the latest DataTables version, 1.10.7.

$.fn.dataTable.ext.order['dom-text'] = function  ( settings, col )
{
   return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
      return $('input', td).val();
   } );
}


 var table = $("#example").DataTable({
   "scrollY": "500px",
   "scrollX": "675px",
   "scrollCollapse": true,
   "paging": false,
   "order": [],
   "deferRender": true,
   "orderClasses": false,
   "columnDefs": [
     { "orderDataType": "dom-text", "targets": [5,6] }
    ]
 });
1
Could you label your question with JQuery if in fact you are using this?Tim Biegeleisen
Notice in the example there is also type: 'string' option, which you're missing.Gyrocode.com

1 Answers

2
votes

SOLUTION

As in the Live DOM Ordering example, you need to use dom-text for sorting <input> elements containing text and dom-text-numeric for sorting <input> elements containing numbers.

/* Create an array with the values of all the input boxes in a column */
$.fn.dataTable.ext.order['dom-text'] = function  ( settings, col )
{
    return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
        return $('input', td).val();
    } );
}

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

$(document).ready(function (){
    $('#example').dataTable( {
        /* ... other options ... */
        "columnDefs": [
            { "targets": 1, "orderDataType": "dom-text-numeric" },
            { "targets": 2, "orderDataType": "dom-text", "type": "string" }
        ]
    } );
});

DEMO

See this jsFiddle for code and demonstration.