Adding parameters to a URL to "pre-filter"

Adding parameters to a URL to "pre-filter"

nickelmedianickelmedia Posts: 12Questions: 0Answers: 0
edited January 2013 in DataTables 1.9
Sorry I am going to use the wrong lingo I'm sure, but what I'm trying to do is create links that have parameters in the URL that will take me to my table and have the search field already filled in with the parameter.

example: http://mysite.com/list/?search=ABC

I'd want that link to take me to my table that lives at http://mysite.com/list/ and have the search box already filled in with "ABC" in it. I got as far as finding this code, which worked, but it's a hardcoded search and I want it to be a variable controlled via the URL.

[code]
$(document).ready( function() {
$('#example').dataTable( {
"oSearch": {"sSearch": "Initial search"}
} );
} )
[/code]

Here is my live example of my current code: http://live.datatables.net/etigif/3/edit

Any help would be greatly appreciated!

Replies

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Use `window.location.search` to get the query string and and use that for your search parameter. You will need to parse the URL formatted query string - there are loads of libraries out there for that kind of thing or just use a trivial regex.

    Allan
  • nickelmedianickelmedia Posts: 12Questions: 0Answers: 0
    Thanks.

    Solved using the following script:

    [code]$.urlParam = function(name){
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (!results)
    {
    return 0;
    }
    return results[1] || 0;
    }[/code]

    changed oSearch to:

    [code]"oSearch": {"sSearch": $.urlParam('search')}[/code]

    I can now search with http://www.mysite.com/list/?search=ABC
  • nickelmedianickelmedia Posts: 12Questions: 0Answers: 0
    edited January 2013
    I was wrong. As soon as I add that oSearch line, it breaks datatables. Is there a better way to call it?

    I've updated my live example here: http://live.datatables.net/etigif/4/edit
  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Don't return `0` since that is not a string. Just return an empty string.

    Allan
  • nickelmedianickelmedia Posts: 12Questions: 0Answers: 0
    Brilliant! Thanks!
This discussion has been closed.