Feb24Written by:slhilbert
2/24/2010 4:06 PM 
We recently had a client ask us if we could pre-populate a form using the values in a querystring. The client has a Paypal form on their website and they wanted to be able to provide a promo code to their affiliates in the form of a URL containing a querystring and have it automatically populate the promo code box.
They also wanted to make sure as their clients navigate through their site that the promo code stays populated in the promo code textbox. We solved this by using a little Javascript and a cookie.
NOTE: The script should fall after the input box. The name of the input box in the example is: oS0
Here is the code:
<SCRIPT type="text/javascript">
//Function to get the specified querystring
//Found at http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx
function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
//Found at http://www.w3schools.com/JS/js_cookies.asp
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
//Found at http://www.w3schools.com/JS/js_cookies.asp
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
//Checking if the promo cookie exists
if (getCookie("LOADMODDIYPROMO").length > 0 )
{
//Promo cookie does exist so populate text field with value from cookie
//Writing the promo code to the promo textbox.
inputObj = document.getElementById('os0');
inputObj.value = getCookie("PROMOCOOKIE");
}
else
{
//Promo cookie doesn't exists so check the querystring
//Getting the querystring values
var urlString = parent.document.URL;
var queryString = urlString.substring(urlString.indexOf('?'),urlString.length);
//Determining if the querystring contains the word PROMO
var pos=queryString.indexOf("PROMO=");
if (pos>=0)
{
//Writing the promo code to the promo textbox.
inputObj = document.getElementById('os0');
inputObj.value = getQuerystring('PROMO');
//Writing a cookie for later user
setCookie("PROMOCOOKIE",inputObj.value,7);
alert("setting cookie");
}
}
</SCRIPT>