Get Jquery data tables to sort on table that contains inputs

喜你入骨 提交于 2020-01-02 05:33:09

问题


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.



来源:https://stackoverflow.com/questions/18333079/get-jquery-data-tables-to-sort-on-table-that-contains-inputs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!