Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
 
 
I don't think this should be closed. That question you linked to shows how to get the query strings, but it does not show how to append it to the <form> action. –  Josh Stodola Dec 16 '09 at 17:40
add comment

2 Answers

up vote 1 down vote accepted
window.onload = function() {
  var frm = document.forms[0];
  frm.action = frm.action + location.search;
}
share|improve this answer
 
Thanks Josh, this worked perfectly. –  Kris Dec 16 '09 at 18:18
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.