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

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

The answer below is decent enough, but I'd say this is the neater solution! Thanks!
What if the url (element.href) already has a parameter (eg, cnn.com?show=true&page=2)? That will cause your method to fail as it will just append an additional question mark.
@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';
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.
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');

2 Comments

jQuery isn't tagged here. You should specify that in order for this to work the user will need to include the jQuery library.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.