1

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.

2
  • See stackoverflow.com/questions/827368/… Commented Dec 16, 2009 at 17:36
  • 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. Commented Dec 16, 2009 at 17:40

2 Answers 2

2
window.onload = function() {
  var frm = document.forms[0];
  frm.action = frm.action + location.search;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.