0

I have a dynamic variable that gets updated by users of a webpage in a script and when the user clicks on a hyperlink I need to be able to send that variable to another webpage. So I need something like

<a href="http://example.com?variable=variableGetter()">Link</a>

to work but I am not sure the exact syntax on how to do this. I already have a getter in my JavaScript I just need to be able to access it when the user clicks on a link.

Doug_O
  • 1
  • 2

2 Answers2

2

You could either use an onclick action to send you to a function that navigates the page for you.

Or

You could update the href attribute anytime that value of variable needs to be changed.

The second option is probably preferable, but it largely depends on what else is going on in the page and how variable is set

Matt Urtnowski
  • 2,556
  • 1
  • 18
  • 36
2

it looks very familiar with this:

How to redirect on another page and pass parameter in url from table?

<a href="#" id="redirectwithid">link</a>

Native JS:

document.getElementById('redirectwithid').setAttribute('href','yoururl?variable=' + variableGetter());

jQuery:

$("#redirectwithid").click(function() {
   var yourVariable = variableGetter();
   if (yourVariable != null) {
      window.location = 'yoururl?variable=' + yourVariable;
   }
});​

Add for Native JS: I don't know your code so just insert the code where you want to update your variable - at the same time the href will change.

Edit:

If you want to add multiple variable like ?variable=1 and a second variable2=2 you can achieve this by adding a & between the variables, like this:

NativeJS:

document.getElementById('redirectwithid').setAttribute('href','yoururl?variable=' + variableGetter() + '&variable2=' + variable2Getter());

JQuery:

$("#redirectwithid").click(function() {
   var yourVariable = variableGetter();
   var yourVariableTwo = variableTwoGetter();
   if (yourVariable != null) {
      window.location = 'yoururl?variable=' + yourVariable + '&' + yourVariableTwo;
   }
});​
Community
  • 1
  • 1
DominikAngerer
  • 6,354
  • 5
  • 33
  • 60