[javascript] Passing Javascript variable to <a href >

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

HTML Part:

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

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


This question is related to javascript

The answer is

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.


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

 this is a <a href ="javascript:openPage()">Link  </a>

Alternatively you could just use a document.write:

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



    function getUrlVars()
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
        hash = hashes[i].split('=');
        vars[hash[0]] = hash[1];
    return vars;

var user = getUrlVars()["user"];
var pass = getUrlVars()["pass"];
var sub  = getUrlVars()["sub"];

    var myApp = angular.module('myApp',[]);

myApp.controller('dropdownCtrl', ['$scope','$window','$http', function($scope, $window, $http) {


     .then(function (response) {$scope.names = response.data.admin;});
    $scope.names = [];


            .then(function (response) {$scope.chapter = response.data.chp;});
           $scope.chapter = [];




<div ng-controller="dropdownCtrl">
<div ng-repeat="a in chapter">
<a href="topic.html?ch={{a.chapter}}" onClick="location.href=this.href+'&user='+user+'&pass='+pass+'&sub='+sub;return false;">{{a.chapter}}</a>

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;

You can also use an express framework

  var id = req.params.id;
  res.render("home.ejs",{identity : id});

Express file, which receives a JS variable identity from node.js

<a href = "/any_route/<%=identity%> includes identity JS variable into your href without a trouble enter

   var scrt_var = 10;
<a id="link">this is a link</a>