1

Having this link how can I get only the ?ref="THIS" part?? Because I want to pick only this part of the link with jQuery and then later use it as a variable.. Is this possible?? I want to do it when I'm loading the page. So:

JavaScript:

$(document).ready(function() GET the variable (var variable = ref="THIS";) if(cookie != null){ $("#"+variable).show().$.cookie("actual" , variable); }); 

Html:

<a href="products.php?ref=oscilobatiente&tipo=7001ad></a> 

2 Answers 2

2

See this fiddle

Edit: I adjusted it so it works with objects now, thanks to some good comments by Thiefmaster

js

$(function() { var url = $("a").attr("href"); var index = url.indexOf('?'); var vars = url.substring(index + 1, url.length).split('&'); var params = {} ; for(var i = 0; i < vars.length; i ++) { var param = vars[i].split('='); params[param[0]] = param[1]; } alert(params.ref); });​ 
Sign up to request clarification or add additional context in comments.

3 Comments

[] the preferred way to create an array (instead of new Array()). However, you do not want an array in this case but an object (var params = {};) as you are using named fields. In case you wonder why your code works anyway: An Array is an object, too, so it can have properties. They won't be counted for its .length though.
@ThiefMaster well there you go then ^^
But when i use it it says undefined in the alert message
2

ok so giving the A tag the id of myLink, you could do (note that the + 4 on the index is so that it doesn't include "ref=":

var myLinkHref = $("#myLink").attr("href"); var ref = myLinkHref.substring(myLinkHref.indexOf("ref=") + 4); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.