Tutorial :Passing Javascript variable to <a href >


<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)



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.


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);  })();  


<script>     var scrt_var = 10;     document.getElementById("link").setAttribute("href",scrt_var);  </script>  <a id="link">this is a link</a>  


<html>    <script language="javascript" type="text/javascript">  var scrt_var = 10;   openPage = function() {  location.href = "2.html?Key="+scrt_var;  }  </script>     this is a <a href ="javascript:openPage()">Link  </a>  </html>  


Alternatively you could just use a document.write:

...HTML  <script type="text\javascript">  var location = "http://";  document.write('<a href="' + location + '">Link text</a>');  </script>  ...the rest  


If you use internationalization (i18n), and after switch to another language, something like ?locale=fror ?fr might be added at the end of the url. But when you go to another page on click event, translation switch wont be stable.

For this kind of cases a DOM click event handler function must be produced to handle all the a.href attributes by storing the switch state as a variable and add it to all a tags’ tail.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »