1

Let's say I'm on a page on my website: http://www.example.com/SearchResults.asp?Search=stackoverflow. Is it possible to use a JavaScript or jQuery code to get the variable "search" from the URL string and populate it into the value of the search box?

Basically I'll have my regular identified search box:

<input type="text" title="Search" id="search_box" />

And a user will search for something, but I will want a JavaScript or jQuery code that will get the value from the "search" variable in the URL string when the customer is on the Search.asp page and add it as the "value" to the input#search.

So the user will be on this page: http://www.example.com/SearchResults.asp?Search=stackoverflow and the search box will look like:

<input type="text" title="Search" id="search_box" value="stackoverflow" />

Thanks

henryaaron
  • 6,042
  • 20
  • 61
  • 80

3 Answers3

2

You could try this function:

function getSearchVariable(variable) 
{
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == variable){
            return unescape(pair[1]);
        }else{
            return false;
        }
    }
}

If this function is present in the sample you mentioned above, all you would call getSearchVariable("Search") to have "stackoverflow" returned.

So in your page, you would have a script element that looks like:

<script type="text/javascript">
    function getSearchVariable(variable) 
    {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            if(pair[0] == variable){
                return unescape(pair[1]).split("+").join(" ");
            }else{
                return "";
            }
        }
    }

    $(document).ready(function(){
        $("#search_box").val(getSearchVariable("Search"));
    });
</script>

Hope that helps!

Andrew Odri
  • 8,868
  • 5
  • 46
  • 55
  • This is also another nice function: (And a little less verbose than mine) http://css-tricks.com/snippets/javascript/get-url-variables/ – Andrew Odri Dec 25 '11 at 22:54
  • I realized I cannot edit these since I barely know anything about JavaScript. The actual pages and id's are different that what I initially posted. The ID of the search input is actually `search_box` and the page is actually SearchResults.asp. What do I change in the code above to make it work for me? – henryaaron Dec 25 '11 at 23:14
  • Wow this works excellently. One problem is when there is nothing in the search box, it says false. I just changed `return false;` to `return ;` and it worked! Another thing is the URL string changes spaces to "+" how can I have the script change the "+" back into spaces. – henryaaron Dec 25 '11 at 23:31
  • Ahh yeah, I had left the false in there for error checking; replacing it with `return "";` if the best bet. I've updated the code to replace pluses with spaces. – Andrew Odri Dec 25 '11 at 23:37
  • Thanks, the pluses are still returning though. Also, another bothersome question, how can I have it only match "Search" I also have the variable "Searching" and when I'm on those pages I see "hing" in the search box. – henryaaron Dec 25 '11 at 23:42
  • Hmm, try the code now. That is very strange with the *hing part... Keep in mind that the plus will now be replaced after the URL is decoded, so any real pluses will be sacrificed. – Andrew Odri Dec 25 '11 at 23:51
  • Wow Awesome. P.S. Would the code be incorrect if I changed `return "";` to `return ;` since I have a value fallback? – henryaaron Dec 26 '11 at 00:07
  • P.P.S. Just realized this is the third question you've helped me with... Thank you so much. – henryaaron Dec 26 '11 at 00:09
  • No worries, I noticed that too :P `return;` is basically the exact same as `return null;`; so if the browser's Javascript engine happens to be kind of strict or the variable ends up somewhere that is expecting a string, it may get converted into actual text null, undefined, or (very unlikely in Javascript) thrown an error. If you use `return "";` the variable will always be an empty string, and you won't run the risk of having a nasty looking null where you don't want it. Hope that makes sense :) – Andrew Odri Dec 26 '11 at 00:19
1

You can use the JQuery URI plugin (shamelessly written by yours truly) to extract any piece of the URL: Specifically, $.uri(window.location.href).at("query").search yields "stackoverflow" for the said URL.

The overall flow would be to register a callback (fired on page-load) to analyze the URL and set the value of that form element, that is:

<script>
  $(document).ready(function () {  
    $('#Search').val($.uri(window.location.href).at("query").search); 
  })
</script>
Itay Maman
  • 30,277
  • 10
  • 88
  • 118
0

JavaScript

document.getElementById('Search').value = [(window.location.search.match(/(?:^|[&;])Search=([^&;]+)/) || [])[1]];

jsFiddle.

The wrapping it with [] means that if the value was not found, it will return an empty string instead of undefined (which would be set to the input's value and shown as the undefined string).

jQuery

$('#Search').val(function() {
    return (window.location.search.match(/(?:^|[&;])Search=([^&;]+)/) || [])[1];
});

jsFiddle.

The (/* get GET param */ || []) is so the code will not error if the GET param was not found.

Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
  • I don't know why it didn't work: `$('#search_box').val(function() { return (window.location.searchresults.match(/(?:^|[&;])Search=([^&;]+)/) || [])[1]; });` the div's id is really search_box and the page's url is actually searchresults.asp. I modified the code accordingly, but it didn't work. Do you know why? – henryaaron Dec 25 '11 at 22:47
  • @user your code is wrong. Why did you put `searchresults` in there? – alex Dec 26 '11 at 00:27