Reputation: 11240
basically I have a link like so:
<a href="file.php?value=this&something=so&please=help">special link</a>
And when I click it, I want to be able to easily refer to the variables.
So for example something like
$(document).ready(function){
$('a').click(function(){
var myvalue = $(this).attr('href........
/// and thats as far as I know!
return false;
});
});
How do I access those variables?
Upvotes: 1
Views: 2202
Reputation: 2453
I'm using a simple function as suggested above - split on the ampersand and again on the equal sign.
var urlObj = location.search
var params = urlObj.slice(1).split("&")
var map = {}
for (var i=0; i < params.length; i++){
var item = params[i]
var key = item.match(/^.*\=/)[0].replace(/\=/,"")
var value = item.match(/\=.*$/)[0].replace(/\=/,"")
map[key] = value
}
Upvotes: 1
Reputation: 88796
jQuery doesn't have support for reading a query string built in (or if it does, I never found it).
You could manually process document.location.search, but then you'd have to manually split it on & (and then again on =) as well as url decode it.
However, there are some jQuery plugins to do this for you:
Strangely, jQuery has a built-in function to do the opposite... $.param(obj) will turn an array or javascript object into a query string for you.
Upvotes: 3
Reputation: 9159
And if you want a really nice function to take a URL and give you all the parts, I recommend the ever popular PHP.JS function parse_url
Upvotes: 1
Reputation: 1038780
There's nothing built-in jQuery that will allow you to do this. You could use a plugin to parse urls. So basically your code could look like:
$('a').click(function(evt) {
var myValue = jQuery.url.setUrl(this.href).param('value');
evt.preventDefault();
});
Upvotes: 0
Reputation: 5693
To merely grab them you'd need something like this:
var urlstring = window.location.search;
To manipulate them, there are already answers on SO, for instance here.
Upvotes: 1
Reputation: 19446
location.search is what I would use, not sure why you need jquery. Also if you're dealing with links, try using link.search
this quick snippet works
<a href='http://www.google.com/?id=asdfasdfasdf' id='tes1'>asdfasdf</a>
<input type='button' onclick='alert(document.getElementById("tes1").search)'>
Upvotes: 1