View Full Version : parse a URL and place item into hidden form field

07-06-2010, 08:57 PM
Hello all.

I have created a snippet of javascript code that will do the following:

1. read the window URL
2. depending on the window URL, a word will be placed into a hidden form field.
3. Person submits form...etc., etc.

Here is what I have.

Let's say that I have a single landing page with a simple form on it. I would like to reference the referred URL by pulling a part of the window URL into a hidden field of the form. Let's say the three URLs are:


I have created a javascript that takes the exact URL and check for equality. If the URL is equal, it will place the corresponding id into the hidden form field. See my code below.

<script type="text/javascript">
var lead_source = window.location.href
if (lead_source == "http://www.whatever.com/index.htm?id=ref1")
document.writeln("<input type=hidden name='lead_source' id='lead_source' value='ref1'>");
else if (lead_source == "http://www.whatever.com/index.htm?id=ref2")
document.writeln("<input type=hidden name='lead_source' id='lead_source' value='ref2'>");
else if (lead_source == "http://www.whatever.com/index.htm?id=ref3")
document.writeln("<input type=hidden name='lead_source' id='lead_source' value='ref3'>");

What I am looking to do is modify the code to only look at the "id" variable, not the entire URL. That way, if I add any additional items to the URL I will not have to change the code. I guess I am looking for an extra step of parsing the URL...maybe.

Thanks for your help

07-06-2010, 10:26 PM

07-06-2010, 11:19 PM
Although...don't. You shouldn't use JavaScript for this. Using a server-side language such as PHP makes this much more accessible to people with it disabled.