4

I've got a table that is a mixture of static <td> and inputs (wrapped in td) <td><input></td>.

To sort through and filter the data ive used the Jquery data tables plugin the only problem is that it won't sort the <input> tags it just leaves them at the bottom of the sorted list (or top if you click it twice), although the search function still works on all cells.

Is there a way to get Data Tables to recognize the values inside of the input tags and be able to sort them, I'm looking to do this with hybrid data, i.e. some static td values (generated from calculations on the server side) and some inputs?

I've made a jsfiddle of the problem here - http://jsfiddle.net/qE2wV/5/

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
sam
  • 9,486
  • 36
  • 109
  • 160
  • Updated answer for **version 1.10**+: http://stackoverflow.com/questions/11376469/can-datatables-sort-a-column-with-an-input-field/29221907#29221907 – Rhys Stephens Mar 23 '15 at 22:55

2 Answers2

5

Try writing a custom sorting function which could retrieve value of the input if the row has input else the text. See below,

function getValue(x) {
    if (x.indexOf('input') >= 0) {
        return $(x).val();
    }         
    return x;
}

Now, use this function to implement the custom comparator like below,

jQuery.fn.dataTableExt.oSort['cust-txt-asc'] = function (a, b) {
    var x = getValue(a);
    var y = getValue(b);
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};

jQuery.fn.dataTableExt.oSort['cust-txt-desc'] = function (a, b) {
    var x = getValue(a);
    var y = getValue(b);
    return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};

Initialize the datatable with the above search comparators,

$('#example').dataTable({"aoColumns": [
        { "sType": "cust-txt" },
        { "sType": "cust-txt" },
        { "sType": "cust-txt" },
        { "sType": "cust-txt" }
    ]});

DEMO: http://jsfiddle.net/eLTUa/

Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
  • 1
    Thanks @vega - This works great, i also checked out your fixed TableRC plugin, it looks like a really handy way to mimic the 'frozen' column feature of excel, when using html data tables – sam Aug 28 '13 at 20:28
  • @sam Thanks for trying out my table plugin. I really appreciate it. – Selvakumar Arumugam Aug 29 '13 at 00:14
1

This DataTables example shows a sortable DataTable where the fields are inputs

Code for initialization is included.

I did not post it here, as there is a copyright notice and I am aware some of datatables stuff isn't free, like the editor.

Paul
  • 26,170
  • 12
  • 85
  • 119
  • Thanks, do you know if it works with hybrid data, ie. some static `` and some `` in the same rows and same columns. – sam Aug 20 '13 at 13:11