I'm looking for a robust way of dynamically injecting a query string parameter when a visitor clicks on a static anchor-link.
For example a link:
<a href="http://www.johndoeslink.com">Test</a>
I want to pass a query string to the next page but have to assign the value dynamically. How can I achieve this?
I know this is simple I'm just missing something obvious! =\
Thanks in advance,
John d
There are many ways you could do this. Below I've listed two very simple methods. Here I'm assuming you already have a reference to your a
element (here I've called this element
):
href
attributeelement.href += '?query=value';
element.addEventListener('click', function(event) {
// Stop the link from redirecting
event.preventDefault();
// Redirect instead with JavaScript
window.location.href = element.href + '?query=value';
}, false);
If you already know the value to append when loading the page then you can add this when the document is ready : If you're using JQuery use this:
$( 'class' ).attr( 'href', function(index, value) {
return value + '?item=myValue';
});
Otherwise (plain Javascript):
var link = document.getElementById("mylink");
link.setAttribute('href', 'http://www.johndoeslink.com'+'?item=myValue');
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