Prepopulate the text box for dataTables individual column searching

Viewed 211

this should be easy but all the examples I can find are specific to the "general search" text box. I'm trying to prepopulate an individual column search box, for example the "Name" field.

prepopulate the name field

I don't need the code to do the search, just code to put a value in that "Search Name" text field.

2 Answers

There are 2 steps you can take to achieve this.

Step 1:

Use the searchCols option to set up your initial search terms. For example:

"searchCols": [
  { "search": "sat" }
]

This will cause column 1 to be filtered on the string sat.

If you want to use additional or different column filters, you can use null to skip columns - for example:

"searchCols": [
  null,
  { "search": "foo" }
  null,
  { "search": "bar" }
]

The above example will filter the 2nd and 4th columns.

Step 2:

You can take the existing code which creates the input fields in the table's footer cells, and modify that code to (a) use an index, and then (b) use the index to target the specific column(s) you want to pre-populate:

$('#example tfoot th').each(function ( idx ) {
  var title = $(this).text();
  $(this).html('<input type="text" placeholder="Search ' + title + '" />');
  if ( idx === 0 ) {
    $(this).find( 'input' ).val( 'sat' );
  }
});

In the above fragment, I took the code linked to in the question and added the idx variable, and then used that to target the first input field, and populate it with "sat".

Without step 2, the DataTable will not show you the values being used to perform filtering.

        initComplete: function () {
        this.api().columns().every( function () {
            var column = this;
            if ($(column.header()).hasClass('datatable_search')) {
                var that = this;
                //player var taken from url 
                if (column.header().innerText.includes('Players') && players.length){
                    //prepopulate the input field                        
                    $( 'input', this.header() ).val(players)
                    //use the url.players arg in the search and redraw 
                    this.search( players ).draw();
                }
                $( 'input', this.header() ).on( 'keyup change clear', function () {
                    if ( that.search() !== this.value ) {
                        that
                            .search( this.value )
                            .draw();
                    }
                } ); 
Related