Prepopulating the Search text box

Prepopulating the Search text box

justStevejustSteve Posts: 49Questions: 8Answers: 1

I'm passing a search from a non-DT control through my server, getting my results and rendering them to a DT grid. I'd like the string that was used for the search to be present in DT's search control after the grid is rendered.

thanks!

This question has accepted answers - jump to:

Answers

  • ThomDThomD Posts: 334Questions: 11Answers: 43

    In your initComplete config, add this code.

                    $('#example_filter input').val('Mary');
                    this.api().search('Mary').draw();
    

    The table ID is "example" and the search value is "Mary"

  • jLinuxjLinux Posts: 981Questions: 73Answers: 75
    edited October 2015 Answer ✓

    @justSteve - What I did was create a function that would execute via initComplete, it would look for any hash value in the URL, if it was there, it would apply that in the search. Also, whenever something is searched for, it will change the #hash value, that way you can copy and paste the URL and the search will automatically be applied..

    $('#data-table').DataTable( {
        search: true,
        searchHighlight: true,
        initComplete: function( settings, json ) {
            auto_search(this);
        }
    } );
    
    function auto_search($dt){
        var $api = $dt.api();
    
        // Set the search text in the URL hash whenever a search is executed
        $api.on( 'search.dt', function () {
            window.location.hash = $api.search();
        } );
    
        // See if a search string is set in the URL hash, if so, execute a DT search
        var search_str = window.location.hash.substring(1);
    
        // Filter on load if theres anything in the hash
        if(search_str) {
            $api.search( search_str ).draw();
        }
    }
    

    Oh, and as you can see, I applied the nifty little searchHighlight plugin I found on here, created by Bartek Szopka. Iv you dont wait it, just remove the searchHighlight: true, line. I like it because it kinda makes the viewer realize "Hey, im viewing a table that has filters applied to it!"

  • justStevejustSteve Posts: 49Questions: 8Answers: 1

    Loving the idea of cutting/pasting searches.

  • jLinuxjLinux Posts: 981Questions: 73Answers: 75

    Its definitely more useful than I even thought it would be. People just filter the table and copy/paste it in emails, and the exact results are shown. I was thinking about doing the same thing for sorting and maybe even page length.

    Did you end up using it? Just curious

  • jLinuxjLinux Posts: 981Questions: 73Answers: 75
    edited November 2015 Answer ✓

    @justSteve I created a function to update the hash with the page, page length, ordering and search string.

    $(document).ready( function () {
      var table = $('#example').DataTable({
        initComplete: function(){
          DT.keep_conditions( this );
        }
      });
    } );
    
    DT = {
        get_api: function ( dt ){
            if( ! $.fn.DataTable.isDataTable( dt ) && ! ( dt instanceof $.fn.dataTable.Api ) )
                throw new Error('Not a table or an API instance');
    
            return new $.fn.dataTable.Api( dt );
        },
       
        keep_conditions: function ( dt ){
            dt = DT.get_api( dt );
    
            // Change the URL Hash for every change
            dt
                .on( 'search.dt', function () {
                    update_hash();
                } )
                .on( 'order.dt', function () {
                    update_hash();
                } )
                .on( 'page.dt', function () {
                    update_hash();
                } )
                .on( 'length.dt', function ( e, settings, len ) {
                    update_hash();
                } );
    
            // Process the hash string on load
            process_hash();
    
            // Use the query_string() function to break down the hash string
            // and re-draw the DT instance with the specified settings
            function process_hash(){
                var hash = query_string();
    
                if( ! hash ) return;
    
                if( hash.order )
                    dt.order( hash.order.split(':') );
    
                if( hash.search )
                    dt.search( hash.search );
    
                if( hash.page )
                    dt.page( parseInt(hash.page ) );
    
                if( hash.length )
                    dt.page.len( parseInt( hash.length ) );
    
                dt.draw();
            }
    
            // Update the URL hash by processing the DT instance settings (page,
            // length, search, etc) and setting the URL hash string value
            function update_hash(){
                var hash = [];
    
                if( dt.order()[ 0 ] )
                    hash.push( 'order=' + dt.order()[ 0 ][ 0 ]+':'+dt.order()[ 0 ][ 1 ] );
    
                if( dt.search() )
                    hash.push( 'search='+dt.search() );
    
                if( dt.page.info() )
                    hash.push( 'page='+dt.page.info().page );
    
                if( dt.page.len() )
                    hash.push( 'length='+dt.page.len() );
    
                window.location.hash = hash.join('&');
            }
    
            // Process the URL hash into an object 
            function query_string(){
                var query_string = {};
                var query        = window.location.hash.substring(1);
                var vars         = query.split("&");
    
                for ( var i = 0; i < vars.length; i++)  {
                    var pair = vars[ i ].split ( "=");
                    // If first entry with this name
                    if ( typeof query_string[ pair [ 0 ] ] === "undefined") {
                        query_string[ pair [ 0 ] ] = pair [ 1 ];
                        // If second entry with this name
                    } else if ( typeof query_string [ pair [ 0 ] ] === "string") {
                        query_string[ pair [ 0 ] ] = [ query_string [ pair [ 0 ] ], pair[ 1 ] ];
                        // If third or later entry with this name
                    } else {
                        query_string[ pair [ 0 ] ].push ( pair [1 ]);
                    }
                }
    
                return query_string || false;
            }
        }
    };
    
  • justStevejustSteve Posts: 49Questions: 8Answers: 1

    re: am i using...? - absolutely and with many thanks!

  • jLinuxjLinux Posts: 981Questions: 73Answers: 75
    edited November 2015

    I think im gonna make it a DT plugin, simple enough. Just include the script, then something like

    $('#whatever').DataTables({
        keepConditions: {
            page: true,
            length: true,
            search: true,
            order: true
        }
    })
    

    Or..

    $('#whatever').DataTables({
        keepConditions: true // All
    })
    

    What do you think? would it be useful?

    Ive actually got a few other DT functions that I made to be able to work on just about any table, I might turn some of the others into plugins as well, check the functions out here, the comments should be description enough

  • jLinuxjLinux Posts: 981Questions: 73Answers: 75
    edited November 2015

    @justSteve - You got me to make my first DT Plugin!

    Thread here

This discussion has been closed.