18

Possible Duplicate:
Get query string values in JavaScript

how can i get the get variable in javascript?

i want to pass it in jquery function.

function updateTabs(){

            //var number=$_GET['number']; how can i do this?
        alert(number);
        $( "#tabs" ).tabs({ selected: number });

    }
1

3 Answers 3

57
var $_GET = {};
if(document.location.toString().indexOf('?') !== -1) {
    var query = document.location
                   .toString()
                   // get the query string
                   .replace(/^.*?\?/, '')
                   // and remove any existing hash string (thanks, @vrijdenker)
                   .replace(/#.*$/, '')
                   .split('&');

    for(var i=0, l=query.length; i<l; i++) {
       var aux = decodeURIComponent(query[i]).split('=');
       $_GET[aux[0]] = aux[1];
    }
}
//get the 'index' query parameter
alert($_GET['index']);
Sign up to request clarification or add additional context in comments.

7 Comments

I think unescape() needs to be run at line 9 in your code. Apart from that, this is a good solution.
Much better to use decodeURIComponent for both: parameter name and parameter value.
Don't you mean if (...index('?') !== -1)? That's a big difference.
@phileaton you're right. I have no idea how did that slip and... how everyone else did the same until now. Thanks.
split('&'), =>split('&');
|
10

Write:

var $_GET=[];
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(a,name,value){$_GET[name]=value;});

Then $_GET['number']

3 Comments

Don't create variables in JS without var. I'd recommend avoiding starting variable names with $ in JS, it isn't typical. Don't use arrays to hold key/value pairs, use plain objects for that.
@Quentin: The dollar-sign in front of variables is typically used as a convention for jquery objects. var $rows = $("tr") for example.
@JordanArseno — I never said it wasn't allowed by the standard, just that it wasn't typical for JavaScript.
-3

Try this

if (location.search != "")
{
    var x = location.search.substr(1).split(";")
    for (var i=0; i<x.length; i++)
    {
         var y = x[i].split("=");
         alert("Key '" + y[0] + "' has the content '" + y[1]+"'")
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.