I was recently tasked with setting up a payment form that would span across two pages. The second form was dependent on information from the first so I needed to pass some data via the query string in order to update the second form.

After completing the first page of the form, the user would click an anchor and then be directed to the second form.

One of the most common ways to override an anchor’s behavior using JavaScript is to setup an event handler for it’s click event and then prevent the default action from happening.

In the context of setting up an anchor, this often looks like this (in jQuery):

$('#my-link').click(function(evt) {
  window.location = 'http://MyDomain.com';

Though there’s nothing technically wrong with that, I’m much more of a fan of letting elements and languages serve their purpose as much as possible so having JavaScript redirect the page rather than an anchor felt odd.

So rather than manipulate the window object, I setup the anchor, gave it an empty href attribute, and an ID so I could easily access it:

<a id="checkout" href="javascript:;"> Complete Checkout </a>

Next, I setup the event handler for the anchor to read the form elements, build up the URL by setting the new query string variables, and then apply the new URL string to that anchor’s href:

$('#support').click(function(evt) {

  var sUrl = $(this).attr('href');

  sUrl += '&payment_method=' + $('#donate-form input[type=radio]').val();
  $('#checkout').attr('href', sUrl);


Now the URL is created by a series of events triggered by the user, applied to the anchor, and no additional anchor event manipulate had to be done.