Friday, May 24, 2013

How To- Get Query String Value using Java Script

Query String Value using Java Script
In web application development, we all are well aware of Query String and Its uses. We can easily retrieve the Query String values from URL on server-side, but sometimes we need to find the Query String values from URL on client-side i.e using Java Script. But in Java Script, there is no standard way or function to get the Query String values from URL. So here I am explaining how can you get the Query String values from URL using Java Script.

In previous posts, I explained Page Scroll to Top with jQuery, Automatically Refresh Page Using Java Script , How to Create a Textarea Character Counter, Animated Sliding Recent Post Widget For Blogger, Change Input to Upper Case using Java Script, Calculate Age from Date of Birth Using Java Script, jQuery .toggleClass() example and some other articles related to jQuery, Java Script etc.

The following Java Script code snippet facilitates you to retrieve the query string key value. You can also pass the default value if the key value is not find. Here is the function-

function getQuerystringValue(key, defaultValue)
{
    if (defaultValue==null)
    {
        defaultValue="";
    }
    //Gives the query string with '?'
    var search = unescape(window.location.search);
    if (search == "")
    {
        return defaultValue;
    }
    //Gives the query string except '?'
    search = search.substr(1);
    var params = search.split("&");
    for (var i = 0; i < params.length; i++)
    {
        var pairs = params[i].split("=");
        if(pairs[0] == key)
        {
            return pairs[1];
        }
    }
    return defaultValue;
}
Above function excepts two parameter one is "key" i.e query string name whose value you want to retreive and second is "defaultValue" which you want to return if "key" value is not found.
For example: In url : http://manish4dotnet.blogspot.com?author=manish, If you want to get the value of "author" from this url then you have to use the above function as shown below-
var author=getQuerystringValue('author','No author found');
I hope this article will be helpful for you. I would like to have any feedback from you. Your valuable feedback, question, or comments about this article are always welcome.

No comments:

Post a Comment

If You Enjoyed This Post Please Take 5 Seconds To Share It.

^ Scroll to Top hgpromo