问题
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