DataTables - dynamically set columns searchable

守給你的承諾、 提交于 2019-12-11 04:13:51

问题


I need to set the searchable property of a column dynamicaly (after table init). Is there a solution? The use-case is, that I'm using the button extension to toggle column-visibility. But I wan't that only visibile columns are searched.


回答1:


I wanted to add "filter buttons" to the table. They should search(filter) just in one excluded & hidden & not-searchable column.

  • excluded & hidden because the user should not be able to see it
  • not searchable because I wanted to exclude it from the global search.

In multiple support-forums the dt. author promises to implement this functionality, but until this day he didn't. But I did find a thread how you can do it on your own.

But you would have to change it up a bit. My Version:

    $.fn.dataTable.Api.register("isColumnSearchable()", function(colSelector) {
        var idx = this.column(colSelector).index();
        return this.settings()[0].aoColumns[idx].bSearchable;
    });

    $.fn.dataTable.Api.register("setColumnSearchable()", function(colSelector, value) {
        if(value!==this.isColumnSearchable(colSelector)) {
            var idx = this.column(colSelector).index();
            this.settings()[0].aoColumns[idx].bSearchable = value;
            if(value===true)
             this.rows().invalidate();
        }
        return value;
    });

My setFilterFunction:

function setFilter(table,col,value){
    if(value== undefined || value=="" || value==0) {
        value = "";
        table.rows().invalidate();
    }
    else {
        value = "\\b" + value + "\\b";
    }
    var oldsearchable = table.isColumnSearchable(col);
    if (!oldsearchable)
        table.setColumnSearchable(col, true);
    table.column(col).search(value,true).draw();
   if (!oldsearchable)
        table.setColumnSearchable(col, false);
} 

The important part is the

this.rows().invalidate();

this is very costly, but you would have to clear the internal cache of the DataTable in order for the workaround to work (Also in order for filter Buttons and global search to work together). I really hope this functionality get integrated into the core soon!



来源:https://stackoverflow.com/questions/39912395/datatables-dynamically-set-columns-searchable

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