3

I have the following code working to pass a URL parameter to a form tag:

<script type="text/javascript">
  function getQueryVariable(variable) { 
 var query = window.location.search.substring(1); 
 var vars = query.split("&"); 
 for (var i=0;i<vars.length;i++) { 
 var pair = vars[i].split("="); 
 if (pair[0] == variable) { 
   return pair[1]; 
    }
  }
}
 function onLoad() {
var value = getQueryVariable("ID");
var e = document.getElementById('your-field');
e.value = value;
}
</script>

And...

<body onload="onLoad()">
 <!-- your form and hidden field goes here -->
 <input type="hidden" name="your-field" id="your-field" />

How can I pass the same value to an HTML link so that the end result would be:

<a href="http://www.mysite.com?source=[ID]" >

Where [ID] is the whatever piece of code that is needed to add the parameter to the link?

Thanks in advance.

2 Answers 2

9

You should give an id to you link, like this:

<a id="YOUR_ID" href="#" >

And then you have two ways to solve the problem, use pure Javascript or use jQuery:

IF you use jquery you can use your onLoad function and inside inject the following:

var url = "http://www.mysite.com?source=" + value;
$("#YOUR_ID").attr("href",url)

OR using pure javascript:

var url = "http://www.mysite.com?source=" + value;
var element = document.getElementById('YOUR_ID');
element.setAttribute("href",url)
Sign up to request clarification or add additional context in comments.

Comments

1

Change the function onload to this:

function onLoad() {
   var value = getQueryVariable("ID");
   var e = document.getElementById('your-field');
   e.value = value;

   var url = "http://www.mysite.com?source=" + value;
   var element = document.getElementById('YOUR_<A>_ELEMENT_ID');
   element.setAttribute("href",url)
}

I'm using the piece of code that Joao Almeida suggested so his example using jQuery works good too.

Good Luck!

1 Comment

Hi and thanks :) Excuse my ignorance but... what should the a href tag look like? Also, I have 3 different a href tags that need the value to be appended... will the code above work for any number of links?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.