4

I'm having trouble reading a query string with Jquery. What I want to do is read the query string and based on what it says scroll to a certain place or element.

here is my code

    $(document).ready(function () {
        var name = getQueryParam("id")
         { var pairs = location.search.substring(1).split('&'); for (var i = 0; i < pairs.length; i++) 
         { var params = pairs[i].split('='); if (params[0] == param) { return params[1] || ''; } } return undefined; }; })(jQuery);

        if ( name == 1){
        scrollTo(0, 800);
        }
    });
poerg
  • 157
  • 1
  • 2
  • 10

2 Answers2

26

You can use this function to get query string value:

function getParameterByName( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

Example:

var param = getParameterByName('yourVar');
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • I'm still not quite sure how to implement this. Any chance you could tell me what I'm doing wrong function getParameterByName( name ) { name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexS = "[\\?&]"+name+"=([^]*)"; var regex = new RegExp( regexS ); var results = regex.exec( window.location.href ); if( results == null ) return ""; else return decodeURIComponent(results[1].replace(/\+/g, " ")); } var param = getParameterByName('id'); if ( id == 1){ scrollTo(0, 800); } }); – poerg Dec 28 '10 at 18:49
  • 2
    @poerg: When you alert `param` eg `alert(param)`, what does it show? – Sarfraz Dec 28 '10 at 18:51
3

Slightly easier code for doing this: (source: http://jquerybyexample.blogspot.com/2012/05/how-to-get-querystring-value-using.html)

function GetQueryStringParams(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) 
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) 
        {
            return sParameterName[1];
        }
    }
}
Nielsm
  • 289
  • 1
  • 5
  • 18