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
named fruit
variable when going to a.html
. How can I do this in JavaScript or jQuery?
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');
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With