Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Javascript variable to <a href >

Tags:

javascript

<script language="javascript" type="text/javascript"> var scrt_var = 10;  </script> 

HTML Part:

<html>  this is a <a href ="2.html & Key= scrt_var">Link  </a> </html> 

I just want to sent the javascript variable to link (url parameter)

No AJAX

like image 246
joe Avatar asked Jun 10 '09 11:06

joe


People also ask

Can we pass variable in href?

href”, append the variable to it (Here we have used a variable named “XYZ”). Then we need to append the value to the URL. Now our URL is ready with the variable and its value appended to it. In the example below, we will append a variable named 'XYZ' and its value is 55.

How do I add a variable to a URL?

To add a URL variable to each link, go to the Advanced tab of the link editor. In the URL Variables field, you will enter a variable and value pair like so: variable=value. For example, let's say we are creating links for each store and manager.

How set JavaScript variable in HTML?

You cannot use js variables inside html. To add the content of the javascript variable to the html use innerHTML() or create any html tag, add the content of that variable to that created tag and append that tag to the body or any other existing tags in the html.

Do HREF in JavaScript?

In JavaScript, you can call a function or snippet of JavaScript code through the HREF tag of a link. This can be useful because it means that the given JavaScript code is going to automatically run for someone clicking on the link. HREF refers to the “HREF” attribute within an A LINK tag (hyperlink in HTML).


2 Answers

If you want it to be dynamic, so that the value of the variable at the time of the click is used, do the following:

<script language="javascript" type="text/javascript"> var scrt_var = 10;  </script> <a href="2.html" onclick="location.href=this.href+'?key='+scrt_var;return false;">Link</a> 

Of course, that's the quick and dirty solution. You should really have a script that after DOM load adds an onclick handler to all relevant <a> elements.

like image 67
Blixt Avatar answered Sep 18 '22 21:09

Blixt


put id attribute on anchor element

<a id="link2"> 

set href attribute on page load event:

(function() {     var scrt_var = 10;     var strLink = "2.html&Key=" + scrt_var;     document.getElementById("link2").setAttribute("href",strLink); })(); 
like image 24
Andrija Avatar answered Sep 17 '22 21:09

Andrija