tags:

views:

368

answers:

2

I have an html page that people access using an affiliate link, so it has affiliate code in the url (http://www.site.com?cmpid=1234&aid=123). I want to add the cmpid and the aid to the form action url (so when submitted, it submits to the url /form.aspx but adds the cmpid and aid to the end, ie: form.aspx?cmpid=1234&aid=123).

I have no other option than javascript. I can't make this page php or aspx.

+1  A: 
window.onload = function() {
  var frm = document.forms[0];
  frm.action = frm.action + location.search;
}
Josh Stodola
Thanks Josh, this worked perfectly.
Kris
A: 

You can get access to the query string by location.search. Then you should be able to append it onto the form's action directly, something like the following:

// Get a reference to the form however, such as document.getElementById
var form = ...;

// Get the query string, stripping off the question mark (not strictly necessary
// as it gets added back on below but makes manipulation much easier)
var query = location.search.substring(1);

// Highly recommended that you validate parameters for sanity before blindly appending

// Now append them
var existingAction = form.getAttribute("action");
form.setAttribute("action", existingAction + '?' + query);

By the way, I've found that modifying the query string of the form's action directly can be hit-and-miss - I think in particular, IE will trim off any query if you're POSTing the results. (This was a while ago and I can't remember the exact combination of factors, but suffice to say it's not a great idea).

Thus you may want to do this by dynamically creating child elements of the <form> that are hidden inputs, to encode the desired name-value pairs from the query.

Andrzej Doyle