Sergio Sergio - 5 months ago 6
Javascript Question

How can I change the href of an anchor after it has been clicked?

I have a page that pulls in data via AJAX. As well as this I have a link to download said data as a CSV file.

The problem I have is that upon I need to pass some parameters along with the click event so that the server can return the correct CSV file.

Without any processing the link looks like this:

<a href="/manager/TargetResults.csv" class="black">Download Target Reports</a>


This then fires off an ASP.NET MVC Controller action that returns the CSV. What I want to do though is pass two parameters along in the query string. Initially I thought that I could intercept the click event and add data to the query string like so:

var holder = $('.hidden-information').first();
var newOutlets = $('input[name="newoutlets"]', holder).val();
var queryDate = $('input[name="enddate"]', holder).val();
var anchor = $(this);
var link = anchor.attr('href');
link = link + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
anchor.attr('href', link);


It would seem that changing the href at this stage will not update the link in time and the URL will be as it was when it hits the server?

Is it possible to change a URL after it has been clicked or do I need to look at another method?

Thanks

Answer

You could redirect the window yourself, like this:

var holder = $('.hidden-information').first();                                   
var newOutlets = $('input[name="newoutlets"]', holder).val();
var queryDate = $('input[name="enddate"]', holder).val();
window.location.href = this.href + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
return false; //prevent default going-to-href behavior

Or, whatever is updating those hidden fields, update the link then instead of when it's clicked, for example:

$("#someField").change(function() {
  var holder = $('.hidden-information').first();                                   
  var newOutlets = $('input[name="newoutlets"]', holder).val();
  var queryDate = $('input[name="enddate"]', holder).val();                              
  $("a.black").attr("href", function() {
    return "/manager/TargetResults.csv" + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
  });
});

The main difference is this still allows normal click behavior to work, ctrl+click, etc.