Change a column's searchability on the fly
Change a column's searchability on the fly
I'm using ColVis, and I want to make it so that when a column is made visible, it is searchable. But then when a column is hidden using ColVis, I want to make it not searchable.
I can't find a way to do this through the API, so I tried modifying the settings directly while in the column-visibility.dt event.
The change to the settings object does seem successful because when I use the console to check the bSearchable value for the applicable column using $($.fn.dataTable.fnTables(true)).dataTable().fnSettings().aoColumns, it does seem to have the correct value.
However the problem is that the search box does not seem to respect this change to the settings.
http://live.datatables.net/caziperu/1/edit?js,output
In this example, when I hide the Name column using the 'Show/hide columns' button, then use the console to check $($.fn.dataTable.fnTables(true)).dataTable().fnSettings().aoColumns[0].bSearchable, everything looks good. It's false like it's supposed to be. Then if I type 'Angelica' into the search box, her record still comes up as if that column was still searchable.
Does the search function use a different copy of settings? I know the documentation says not to modify settings directly ( https://datatables.net/reference/api/settings() ), but I wasn't able to find another way to do this. Does anybody know?
I'm using DataTables 1.10.6 and ColVis 1.1.2 in my environment, but the results are the same when using the versions found on live.datatables.net.
This question has an accepted answers - jump to answer
Answers
Hi,
At he moment there is no API method to toggle the searchable option of a column. That is something I would like to add in future, but I've still to resolve what should happen when you do so and a filter is applied to that column. Should it then not apply a filter to the column at all, or should the current filter turn static and can't be altered (the former is my preference).
Allan
Thanks for the reply Allan.
I would imagine that when a column's searchability is toggled:
* If there is a current filter applied to the column or the table it is reevaluated after the column is toggled. The api function could take a second parameter, much like
redrawCalculations
incolums().visible()
that would allow you to hold off on reevaluating the filter.* If there is a filter applied to the column later on, it should not apply the filter at all.
That's just my opinion though.
In the meantime though, is there any way to toggle the searchable option of a column? Why wouldn't my code example work?
Also, I know you've heard this a million times, but DataTables is awesome and it makes my job so much easier!
Your example won't work as the search cache needs to be invalidated. Use
table.rows().invalidate();
to do that. However, I have to put this - particularly for anyone else that reads this: modifying the settings object is not supported :-)Thank you!
Allan