How to clear a filter upon column visibility button click

How to clear a filter upon column visibility button click

greenman123greenman123 Posts: 15Questions: 7Answers: 0
edited January 2019 in Free community support

Hi,

I've been reading up on these 2 options:

https://datatables.net/extensions/buttons/examples/column_visibility/simple.html
https://datatables.net/extensions/fixedheader/examples/options/columnFiltering.html

I tested these out and look like they will work for my scenario but I have noticed if I filter a column by entering a value and then turn off the visibility of the column the filter is still applied which then means all further filtering you do is reliant on the first filter applied now hidden.

Is there a setting to clear the filter automatically if this occurs? (would seem logical to do so?).

If not I suspect I will be able to do this by somehow applying an ID to each column visibility button which references the filter inputs and clear it that you using a .val('').trigger('change')?

Thanks,

This question has accepted answers - jump to:

Answers

  • colincolin Posts: 15,112Questions: 1Answers: 2,583
    Answer ✓

    Hi @greenman123 ,

    You could listen for column-visibility, and if the column is being hidden, clear the search with column().search(),

    Cheers,

    Colin

  • greenman123greenman123 Posts: 15Questions: 7Answers: 0

    Okay, I took onboard what you said and does work, see here:

    http://jsfiddle.net/e9z8hgwj/

    However if you do this:

    type 'acc' into the position column filter, then turn that column visibility off, it removes the filter - great that bit is fine. But if I make the column visible again the filter input still reads 'acc' even though not filtered, therefore is there a way to somehow reference that input field to clear it's value from the .columns() function?

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736

    The input element used for the column search is a custom HTML element added. Its not a Datatables element. This means that when you clear the search you also need to manually clear the element. Maybe the jQuery html() method will work.

    Kevin

  • greenman123greenman123 Posts: 15Questions: 7Answers: 0
    edited January 2019

    Yes thanks, I understand. I'm struggling to relate the column visibility false on that column to the input field. I need to know from DataTables which column was just hidden so I can go up the DOM tree to get the input.

  • colincolin Posts: 15,112Questions: 1Answers: 2,583
    Answer ✓

    Hi @greenman123 ,

    Yep, you've done most of the work already. This here does the rest - it clear the DataTables search and the input element.

                $('#example thead tr:eq('+column+') th:eq(1) input').val('')
                table.columns(column).search('').draw();
    

    Cheers,

    Colin

This discussion has been closed.