Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit the href link before send the request

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?

like image 602
markzzz Avatar asked Aug 23 '11 09:08

markzzz


People also ask

How do I change a link in href?

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.

How do I change a link in JavaScript?

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.

How do you remove a href?

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 HTML href?

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.


3 Answers

Just modify the href with new href and you are done.

$('.myLink').click(function() {
    $(this).attr("href", this.href + "?param=1");
});
like image 126
ShankarSangoli Avatar answered Oct 17 '22 15:10

ShankarSangoli


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);
});
like image 41
DenisPostu Avatar answered Oct 17 '22 16:10

DenisPostu


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>
}); 
like image 33
pimvdb Avatar answered Oct 17 '22 15:10

pimvdb