1

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?

willdanceforfun
  • 10,674
  • 31
  • 81
  • 121

6 Answers6

3

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.

Powerlord
  • 84,782
  • 17
  • 123
  • 168
1

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)'>
Allen Rice
  • 18,620
  • 13
  • 80
  • 113
1

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.

Community
  • 1
  • 1
montrealist
  • 5,440
  • 10
  • 45
  • 60
1

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

Tony Miller
  • 8,919
  • 2
  • 26
  • 46
1

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
}
saranicole
  • 1,393
  • 1
  • 16
  • 20
0

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();
});
Darin Dimitrov
  • 994,864
  • 265
  • 3,241
  • 2,902