How to pass variable on href?
51,890
Solution 1
The only way that JS can communicate (easily) between URLs is by creating a parameter on your link. For example:
<a href="a.html?fruit=apple" id="a">Hello</a>
On the receiving page, fetch that parameter data. If you are wanting the data embedded into the link purely via JS, you can append to the HREF using something similar to this by using the jQuery library:
$("a").attr("href", '?fruit=' + 'apple');
Solution 2
Just do this on your main page:
<a href="a.html?fruit=apple" id="a">Hello</a>
And on a.html
, add this code:
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
var fruit = getParameterByName('fruit');
<a href="a.html?fruit=apple" id="a">Hello</a>
Solution 3
You can reset the href value by concatenating the existing value with the new value:
var el = document.getElementById('a');
el.href += '?fruit=apple';
console.log(el.href);
<a href="a.html" id="a">Hello</a>
Author by
임지웅
Updated on December 14, 2020Comments
-
임지웅 over 3 years
I am trying to give another variable when
href=""
<a href="a.html" id="a">Hello</a>
Above is my code.
I want to pass value
apple
namedfruit
variable when going toa.html
. How can I do this in JavaScript or jQuery?-
Mohammad over 5 yearsWhat do you mean by when going to a.html?
-
domsson over 5 yearsYou could change the href value from
a.html
toa.html?fruit=apple
using javascript. -
임지웅 over 5 years@Mohammad umm.. what do you mean by when going to a.html? When I click hello then it will go to a.html
-
-
masiboo about 4 yearsThx for the great answer.
-
Jack Bashford about 4 yearsNo worries @masiboo
-
masiboo about 4 yearsperhaps there is another question about the alignment @ stackoverflow.com/questions/60469800/… do u know how to do it?
-
Jack Bashford about 4 yearsNo clue sorry @masiboo
-
masiboo about 4 yearsthx for the answer. perhaps there is another question about the alignment @ stackoverflow.com/questions/60469800/… do u know how to do it?
-
masiboo about 4 yearsthx for the answer. perhaps there is another question about the alignment @ stackoverflow.com/questions/60469800/… do u know how to do it?
-
masiboo about 4 yearsthx for the answer. perhaps there is another question about the alignment @ stackoverflow.com/questions/60469800/… do u know how to do it?
-
avisk over 2 yearsThat's great, but do you know how to actually access that argument?