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
  • 11,044
  • 31
  • 82
  • 122

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
  • 87,612
  • 17
  • 125
  • 175
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
  • 19,068
  • 14
  • 83
  • 115
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,593
  • 12
  • 46
  • 68
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
  • 9,059
  • 2
  • 27
  • 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
  • 2,093
  • 1
  • 23
  • 23
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
  • 1,023,142
  • 271
  • 3,287
  • 2,928