I have this code :
<a class="myLink" href='http://www.website.it/'>Link</a>
<script type="text/javascript">
var stringToSend = "";
$('.myLink').click(function() {
stringToSend="?param=1";
});
</script>
and, as you can see, I'd like to add stringToSend
to the href (so the request will be at http://www.website.it/?param=1).
How can I do it?
To set of modify the value of the href attribute of a link or the <a> tag, you can use the jQuery . attr() method. This method can also be used to get the value of any attribute.
Code for Changing URLs in Link with JavaScript. When you change a link URL with JavaScript, you'll have to use the setAttribute method. Before even touching jQuery, developers should learn about basic yet useful methods like this. The code below changes an href attribute of a link to my website address.
To remove a hyperlink but keep the text, right-click the hyperlink and click Remove Hyperlink. To remove the hyperlink completely, select it and then press Delete.
What is the HTML a href attribute? In HTML, the inline a (anchor) element denotes a hyperlink from one web address to another. All functional a elements must contain the href (hypertext reference) attribute inside the opening a tag. The href attribute indicates the destination of the hyperlink.
Just modify the href
with new href
and you are done.
$('.myLink').click(function() {
$(this).attr("href", this.href + "?param=1");
});
You should also prevent the default behavior like this:
var stringToSend = "";
// Use this to actually navigate to the changed Uri
$('.myLink').click(function(event) {
event.preventDefault();
stringToSend = "?param=1";
window.location.href = $(this).attr('href') + stringToSend;
});
// Use this just to change the Href, without navigating to uri
$('.myLink').click(function(event) {
event.preventDefault();
stringToSend = "?param=1";
var newUri = $(this).attr('href') + stringToSend;
$(this).attr("href", newUri);
});
When clicking, you could stop the current URL, and navigate to another:
var stringToSend = "";
$('.myLink').click(function() {
stringToSend="?param=1";
window.location.href = $(this).attr('href') + stringToSend; // navigate to new URL
return false; // abort navigation to URL from <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