HoodCoderMan HoodCoderMan - 3 months ago 20x
jQuery Question

JQUERY DATATABLE retain filter parameter after refresh

Greeting again, my fellow coders.

Still working with the same DATATABLE...

I was able to add INPUT fields at the top of the table that conducts individual column searches in the DATATABLE.

What I need to do now is retain the parameter entered in the INPUT field (or fields) after the page refreshes.

Here is my code so far:

// header input filters
$('#example1 .filters th').each(function(){
var title = $('#example1 thead th').eq($(this).index()).text();
$(this).html('<input type="text" placeholder="Search '+title+'" />');

// set and print the datatable
var $dataTable = $('#example1').DataTable({
"ajax": 'api/dateset.php',
"iDisplayLength": 25,
"order": [[ 6, "desc" ]],
"scrollY": 580,
"scrollX": true,
"bDestroy": true,
"stateSave": true

// Apply the search to columns
$('input', $('.filters th')[colIdx]).on('keyup change', function(){

If you'll notice in the portion above where I set the $dataTable, you should see "stateSave": true . Using that, when the page refreshes, it does save the parameter search entered by the user, but it doesn't display the text in the INPUT field.

That is where I am stuck.

Here is a visual representation:

Before refresh -

enter image description here

After refresh -

enter image description here

As you see in the 2nd picture, the search is good for BOOKING beginning with TEST222, but the text is no longer visible in the BOOKING INPUT field.

I did come across this post: https://datatables.net/reference/option/stateSaveCallback

But I am not sure how to implement that code into my code. I am not even sure if stateSaveCallback is the right function to use.

If you see an error in my code, or if you know how to apply stateSaveCallback to my code, please enlighten me how to use it.

In LeeLuu Dallas voice, "Pleease....help."

Thank you so much in advance.

May the Fourth be with you.


So after 2 days of searching as well as no answer from SO, I finally found this post: http://live.datatables.net/neqozaj/1/edit

Utilizing that post, I was able to add this piece of code to the overall function:

 var state = $dataTable.state.loaded();
 if ( state ) {
   $dataTable.columns().eq( 0 ).each( function ( colIdx ) {
   var colSearch = state.columns[colIdx].search;

   if ( colSearch.search ) {
     $('input', $('.filters th')[colIdx]).val( colSearch.search );

Using this, I was able to to achieve the effect I wanted. Too bad I cannot upvote my own post.

Thanks anyways, SO.