-1

I'm using jquery to grab a variable in the url (http://website.com?Name=Brian) and setting a javascript variable as such:

var name = getQueryVariable('Name');

Now I'm trying to dynamically update an href property in Unbounce (unbounce.com) as follows:

  document.getElementById('lp-pom-button-181').setAttribute("href","http://google.com?fname=name");

so that I can pass the variable on.

How do I add the 'var name' to the end of the url 'http://google.com?fname=' for the setAttribute href?

Thank you.

1 Answers1

0

Simple string concatenation, combined with encodeURIComponent:

document.getElementById('lp-pom-button-181').setAttribute("href","http://google.com?fname=" + encodeURIComponent(name));

You need encodeURIComponent to ensure that the query string parameter is properly escaped. For instance, to ensure that & (which is a special character in query strings) is correctly encoded as %26.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thank you for the reply T.J. I'll be the first to admit I don't know javascript. PHP is more my playground and I'm a novice at that. I'm using jquery to pull the variables out of the url and I'm pretty sure the variables are already escaped. Just to make sure, I tried adding the variable while also making sure the query string parameter was escaped per your suggestion, and no dice. Thoughts? – brianjambor Mar 06 '14 at 23:11
  • I spoke with a friend who mentioned that I could use jQuery to accomplish the same thing: `code` $('#lp-pom-button-181').attr('href', 'http://google.com?fname=' + name); `code` – brianjambor Mar 07 '14 at 00:10
  • @brianjambor: **If** the text in the variable is already encoded, then obviously you don't have to encode it. But I suspect that text probably isn't. In any case, the above *does* work: http://jsbin.com/senavusu/1 – T.J. Crowder Mar 07 '14 at 08:16