To save the search filtering value in a DataTable and restore it after a refresh, you can use browser storage mechanisms like localStorage
or sessionStorage
. Here's an example of how you can achieve this using localStorage
:
// Initialize DataTable with an id var dataTable = $('#example').DataTable(); // Event listener for search input $('#example_filter input').on('input', function() { var searchValue = $(this).val(); // Save the search value to localStorage localStorage.setItem('dataTableSearchValue', searchValue); }); // Check if there is a saved search value in localStorage var savedSearchValue = localStorage.getItem('dataTableSearchValue'); if (savedSearchValue) { // Apply the saved search value to the DataTable search input $('#example_filter input').val(savedSearchValue); // Perform search with the saved value dataTable.search(savedSearchValue).draw();
In this example, whenever the user types in the search input, the search value is saved to localStorage
with the key 'dataTableSearchValue'
. When the page is refreshed, the script checks if there is a saved search value in localStorage
. If it exists, the script applies the saved search value to the DataTable search input and performs the search.
Please replace 'example'
with the actual ID or class of your DataTable container. Also, consider implementing additional logic to handle cases where the saved search value may not be valid or applicable to your specific use case.