...

View Full Version : parsing a URL to pull a single item and place it into a form field



this_end_up
07-06-2010, 08:58 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:

http://www.whatever.com/index.htm?id=ref1
http://www.whatever.com/index.htm?id=ref2
http://www.whatever.com/index.htm?id=ref3

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'>");
}
}
</script>

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

Old Pedant
07-06-2010, 10:19 PM
// code to parse query string
var querystring = [ ];
if ( location.search.length > 1 )
{
var pairs = location.search.substring(1).split("&");
for ( var p = 0; p < pairs.length; ++p )
{
var pair = pairs[p];
var name = pair[0];
var value = unescape( pair[1].replace(/\+/g, " ") );
querystring[name] = value;
}
}

Once you have done that, you can use

var theIDpassed = querystring["id"]

to get the value of the id=xxx. Note that this also gets a name/value entry in the querystring variable for any pair seen in the url after the question mark.

For a more complete answer, for filling in form fields based on the querystring and dependant on the *types* of those fields, look at post #6 in this old thread:
http://codingforums.com/showthread.php?t=198419



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum