-1

I want to change the href of a link after I click on it:

$('#mylink').click(function() {
    // do something
    $('#mylink').attr('href', 'newURL.php');
    });

<a href=# id=mylink>click</a>

i would assume this would work, but when I click on it, it redirects to new page.

How can I make it change the href after the user has finished clicking?

user1022585
  • 13,061
  • 21
  • 55
  • 75

2 Answers2

1

You could do something like this:

$('#mylink').click(function(e) {
  e.preventDefault();
  $('#mylink').attr('href', 'newURL.php');
  window.location.href = $(this).attr('href');
});

The window.location will take the new url and direct you to it.

edit

As mplungjan has said in the comments, you can simplify this further:

$('#mylink').click(function(e) {
    e.preventDefault(); 
    window.location.href = 'newURL.php';
});

So you don't need to set the href attr directly, you could skip that and just utilise the window.location.href directly

Andy Holmes
  • 7,817
  • 10
  • 50
  • 83
0

use e.preventDefault() on click on link

$('#mylink').click(function(e) {
     e.preventDefault();
    $('#mylink').attr('href','newURL.php');
     console.log("NEW LINK ="+$('#mylink').attr('href'));
     window.location.href=$(this).attr('href');
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>


<a href="" id=mylink>click</a>
Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71