Get Jquery data tables to sort on table that conta

2019-05-08 16:55发布

问题:

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/

回答1:

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/



回答2:

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.