Wednesday, February 09, 2011

JQuery: How To Get URL Parameters & Values

While developing on a Drupal website, I was using the URLFill module to automatically fill in the form fields with some GET variables in the URL (something like http://example.com?var1=value1&var2=value2). For some reason it is not filling-up a Content Taxonomy field where the widget is set as autocomplete. So what I did was to implement the auto-filling of the said field with JQuery. This was the function I used:


$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});


Calling getUrlVars() function would return you the following array:


{
"me" : "myValue",
"name2" : "SomeOtherValue"
}


Typical usage is as follows:


// Get object of URL parameters
var allVars = $.getUrlVars();

// Getting URL var by its nam
var byName = $.getUrlVar('name');


Source: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html

No comments:

Post a Comment