I am trying to update or set a given URL specific query string value on a click of an <a>
element.
I managed to make it work by setting the URL:
<a id="my-link" href="http://example.com/">
$('#my-link').on('click', function(e) {
let url = this.getAttribute('href');
let queryStringKey = 'someKey';
let queryStringValue = encodeURIComponent(someDataObject);
let url += `?${key}=${queryStringValue}`;
e.originalEvent.currentTarget.href = url;
});
But this only works on the first click because it keeps appending the query string.
What I tried was to then save the original URL, set the url using e.originalEvent.currentTarget.href
and then set it back after the click, but it doesn’t work, it just reads the original url instead of the updated one:
<a id="my-link" href="http://example.com/">
$('#my-link').on('click', function(e) {
let originalUrl = this.getAttribute('href');
let queryStringKey = 'someKey';
let queryStringValue = encodeURIComponent(someDataObject);
let updatedUrl += originalUrl + `?${key}=${queryStringValue}`;
e.originalEvent.currentTarget.href = updatedUrl;
this.href = originalUrl; // it then opens this URL instead of the updatedUrl
});
3
Answers
Use the URL API
Note: use
new URL(this.href);
if you do not have a valid URL sincenew URL(this.getAttribute("href"))
will fail onhref="/"
Whenever the url get clicked Remove the additional key value to restore the original link :
I would do so: