12

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

krex
  • 345
  • 3
  • 8
  • 21

2 Answers2

19

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

Modifying the href attribute

element.href += '?query=value';

Using a click event listener

element.addEventListener('click', function(event) {
    // Stop the link from redirecting
    event.preventDefault();

    // Redirect instead with JavaScript
    window.location.href = element.href + '?query=value';
}, false);
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • The answer below is decent enough, but I'd say this is the neater solution! Thanks! – krex Aug 14 '14 at 08:06
  • What if the url (element.href) already has a parameter (eg, http://www.cnn.com?show=true&page=2)? That will cause your method to fail as it will just append an additional question mark. – bperdue Feb 02 '16 at 01:18
  • 3
    @bperdue you can use an `if` statement to check if a `window.location.search` is already present. `if (window.location.search) window.location.href = element.href + '&query=value';` – James Donnelly Feb 02 '16 at 07:53
  • It is much better to just use `element.search = '?query=value'`. This way you don't have to fiddle around with whether or not the element already has a querystring or not, which you might be adding to instead of replacing. – ErikE Aug 04 '16 at 20:38
4

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');
Oualid KTATA
  • 1,116
  • 10
  • 20
  • jQuery isn't tagged here. You should specify that in order for this to work the user will need to include the jQuery library. – James Donnelly Aug 13 '14 at 15:40
  • It is much better to use the `search` property instead of the `href` one. Then you can do `element.search = '?query=value'`. This way you don't have to fiddle around with having to set the domain and path portions of the url. – ErikE Aug 04 '16 at 20:39