0

Using jquery, how do I get the values of each field in a url querystring? (I'm referring to the search= value and offset= value etc.) Sometimes its more than just these three.

<a href="search=sony&offset=20&lang=en" class="more_info">Read More</a>
<a href="search=sony&offset=20&lang=en&period=3" class="more_info">Read More</a>

I tried using $(".more_info").attr("search"), which should have worked, but doesn't.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Norman
  • 6,159
  • 23
  • 88
  • 141
  • 4
    Why should it have worked? The `a` elements clearly don't have `search` attributes. This might help: http://stackoverflow.com/questions/2328913/how-to-use-jquery-to-extract-a-url-parameter-from-a-string – Felix Kling Jul 23 '12 at 18:11
  • It seems you are confusing url and href attribute. – jamjam Jul 23 '12 at 18:13
  • [Possible duplicate](http://stackoverflow.com/questions/1131630/javascript-jquery-param-inverse-function) – Engineer Jul 23 '12 at 18:14

3 Answers3

0

Start by getting the value of the href attribute:

$(".more_info").attr("href")...

Then parse out the values. Try a modified version of the answer to this question:

function getParameterByName(name, query) {
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(query);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

So now you can say:

$(".more_info").each(function () {
    getParameterByName("search", $(this).attr("href"));
});

Try it out an let me know how it goes.

Community
  • 1
  • 1
woz
  • 10,888
  • 3
  • 34
  • 64
0

The attr() function selects an attribute of the element, in this case "href" would be an example of this. If you're attempting to access the URL variable called "search", you would need the following code (assuming the search variable is always first):

$('.more_info').attr('href').split('&')[0].replace('search=', '');

If it isn't always first then this quick-fix will break, otherwise it's nice and simple.

Tom Walters
  • 15,366
  • 7
  • 57
  • 74
-1

try this : $(".more_info").attr('href')

Harish Ambady
  • 12,525
  • 4
  • 29
  • 54