Save and restore the state of all search boxes

Save and restore the state of all search boxes

ApolymoxicApolymoxic Posts: 15Questions: 4Answers: 0
edited July 2016 in Free community support

I am using data tables with multiple search boxes, and stateSave enabled. The table will indeed save the state, but when reloading the table, the search boxes do not save.

For example, I have 3 columns... Book Author, Book Title, and Book ISBN. I have a search box for each column for greater searching power. If I search for "Mark" in author, all results with the name Mark in the author appear, as expected. Refreshing the page, or doing any other action which will force the table to reload (such as adding a book), the saved search results appear, but the search box is blank. To get all the items to reappear, I need to go to the book author search box and press backspace.

So... how can I save the state of the searchByAuthor text box?

Or... how can I get the value that was searched for, and what column it was used on? If I can get that, I can repopulate the correct search box.

Answers

  • ApolymoxicApolymoxic Posts: 15Questions: 4Answers: 0

    I was able to solve this by overriding the keyup in the search boxes to call a function which saves the value of the search box to localStorage.

    Something like this:
    [code]
    $(this).on('keyup change', function () {
    localStorage.setItem($(this).attr('id'), $(this).val());
    if (column.search() !== this.value) column.search(this.value).draw();
    });
    [/code]

    When reloading the page, the page searches localStorage for anything related to the search box. If something is found, it populates the search box.

    Something like this:
    [code]
    $(".searchBox").each(function(){
    if (localStorage.getItem($(this).attr('id')) != "" && localStorage.getItem($(this).attr('id')) != null){
    $(this).val(localStorage.getItem($(this).attr('id')));
    }
    });
    [/code]

    Where each search box has the class "searchBox"

    I feel that there is probably an easier way to do this, but this works (for now).

This discussion has been closed.