persist search value of individual column with statesave

persist search value of individual column with statesave

qshngqshng Posts: 9Questions: 5Answers: 0

I have a datatables with statesave and individual column search enabled following the example in this link.

https://datatables.net/examples/api/multi_filter.html

The issue is when the page is refreshed, the search value for each column will be loaded, however the search textbox all reset to empty, which is causing confusion. Is there a way to also persist the search value in the text box with statesave?

$(document).ready(function() {
    // Setup - add a text input to each footer cell
    $('#example tfoot th').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
    } );
 
    // DataTable
    var table = $('#example').DataTable( {
        stateSave: true
    } );
 
    // Apply the search
    table.columns().every( function () {
        var that = this;
 
        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );
} );

Answers

  • colincolin Posts: 9,822Questions: 0Answers: 1,629

    Hi @qshng ,

    This thread should help, it's asking the same thing.

    Cheers,

    Colin

  • qshngqshng Posts: 9Questions: 5Answers: 0

    @colin Thank you! This helps. It would be nice if the individual columns search comes as part of the Datatable.

  • qshngqshng Posts: 9Questions: 5Answers: 0

    Just wanted to share my solution using stateLoadParams, add the following config to the table options with stateSave=true:
    Note: replace $(".datatable.main tfoot th") with your own selector

      stateLoadParams: function(settings, data) {
        for (i = 0; i < data.columns["length"]; i++) {
          var col_search_val = data.columns[i].search.search;
          if (col_search_val != "") {
            $("input", $(".datatable.main tfoot th")[i]).val(col_search_val);
          }
        }
      }
    
  • colincolin Posts: 9,822Questions: 0Answers: 1,629

    They can't be reinstated automatically as DataTables has no knowledge of what those input elements are - it only knows that a column search was performed, not by the source which may be the API or a select dropdown or an input filter.

Sign In or Register to comment.