0

I found a solution that retains the value of a datatable search filter box after the page refreshes.

What I need to do is also ensure that a blank value can be retained.

When the user clicks the "clear button" and clears the search box, I need to set the value of the filter to blank. So when the page refreshes, the filter is blank.

Here is the input:

<input type="search" id="searchFilter" onkeyup='saveValue(this);' />

And here is the JavaScript:

document.getElementById("searchFilter").value = getSavedValue("searchFilter"); // set the value to this input

//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
  var id = e.id;  // get the sender's id to save it . 
  var val = e.value; // get the value. 
  localStorage.setItem(id, val); // Every time user writing something, the 
  localStorage's value will override . 
}

//get the saved value function - return the value of "v" from localStorage. 
function getSavedValue(v){
  if (!localStorage.getItem(v)) {
    return ""; // You can change this to your defualt value. 
  }
  return localStorage.getItem(v);
}

Here is the clear button click event:

$('.clearFilters').on('click', function()
{
  $('#searchFilter').val("");
  $('#example1').DataTable().search('').draw();
});    

As stated, when the page is refreshed, the last value that was entered in the search is retained.

However, if the user clears the filter, and if the page refreshes, the last value that was entered appears again in the filter.

The filter needs to be blank if the clear button was clicked and the page refreshes.

I'm guessing I need to call the saveValue function from the clear button click event, but wasn't sure how.

halfer
  • 19,824
  • 17
  • 99
  • 186
John Beasley
  • 2,577
  • 9
  • 43
  • 89

1 Answers1

1

I was able to solve my problem by triggering the keyup by setting the value to blank on the clear filter button event:

$('.clearFilters').on('click', function()
{
  $('#searchFilter').val(""); // still needed to make sure the value gets cleared
  $('#example1').DataTable().search('').draw();
  $('#searchFilter').keyup().val(""); // this is what I added to trigger the keyup
});   
John Beasley
  • 2,577
  • 9
  • 43
  • 89