How to get the index of the column that has been hidden or shown through a colvis button?
How to get the index of the column that has been hidden or shown through a colvis button?
In my example, I am using ColVis and ColReorder so the user can reorder the columns at any time and the buttons are also re-ordered. My use case is that a user should be able to search on an individual column so I started working on this based on this example
Works fine without the ColVis buttons. Once a user clicks on a button, the column is shown, but doesn't have a filter on it. My thought was, to simply figure out what the column index was and re-initiate the filter code similar this:
table.on('buttons-action', function (e, buttonApi, dataTable, node, config) {
let i = 0; // buttonApi tells me which button was pressed, but how do I determine the corresponding column index?
// Put the input in the header
let title = $(table, 'thead th').eq(i).text();
$(node).html('<input type="text" placeholder="' + title + '" data-index="' + i + '" />');
// Wireup the event handler
$(table.table().container()).on('keyup', node, function () {
table
.column($(this).data('index'))
.search(this.value)
.draw();
});
});
If there is a better way to approach this, please let me know.
This question has an accepted answers - jump to answer
Answers
Hi @NateG ,
I combined the example that you have, and this one here, to give this example. The input elements are all intact, and correctly search on the relevant column. Hope that does the trick for you,
Cheers,
Colin
Hi @colin it appears even after making some changes to your example that it does indeed work as intended. I figured out that the difference is that in your example and one provided in the documentation, the initialization of the input fields is happening before the initialization whereas in my example (and you wouldn't have seen this because I didn't post my entire script) I am initializing the input fields after the DataTable has already been initialized hence the need for all the extra work in the
buttons-action
event. Once I moved the input field initialization above the DataTable initialization, then it worked as intended.@colin I prefer to have the filters at the top in the thead element. I did a lot of testing on your example and when I move the filters to the top, simply clicking on them triggers the column sort. Is there a way to set up the event to ignore sorting when clicking on the input field?
Hi @NateG ,
You'll need to use a second header row to do that. See this thread here, there's some explanation and an example,
Cheers,
Colin