PDA

View Full Version : Querystring to Cookie to Text Input...



dnix
02-06-2008, 01:31 AM
Hi JS ppls....

Title says it all really, what i'm trying to do is take a querystring name/value pair and write it to a cookie (value only). I am then attempting to populate a text input using the cookie value...

At the moment, i'm only in the test phase, so it's likely attempting to do all this in the one page could be causing problems... I guess time will tell.

So far I can confirm the Querystring is being read and written to the cookie. The problem comes when attempting to get the cookie data and put it in the text field. Any/all suggestions are welcome...

The Javascript


<SCRIPT type="text/javascript" language="Javascript">

function getCookie(NameOfCookie)
{ if (document.cookie.length > 0)
{ begin = document.cookie.indexOf(NameOfCookie+"=");
if (begin != -1)
{ begin += NameOfCookie.length+1;
end = document.cookie.indexOf(";", begin);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(begin, end)); }
}
return null;
}


function setCookie(NameOfCookie, value, expiredays)
{ var ExpireDate = new Date ();
ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));
document.cookie = NameOfCookie + "=" + escape(value) +
((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
alert('NameOfCookie = ' + NameOfCookie)
alert('CookieValue = ' + value)
alert('CookieExpires = ' + expiredays)
}


function delCookie (NameOfCookie)
{ if (getCookie(NameOfCookie)) {
document.cookie = NameOfCookie + "=" +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}

}

function Querystring(qs) { // optionally pass a querystring to parse
this.params = new Object()
this.get=Querystring_get

if (qs == null)
qs=location.search.substring(1,location.search.length)

if (qs.length == 0) return

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
qs = qs.replace(/\+/g, ' ')
var args = qs.split('&') // parse out name/value pairs separated via &

// split out each name=value pair
for (var i=0;i<args.length;i++) {
var value;
var pair = args[i].split('=')
var name = unescape(pair[0])

if (pair.length == 2)
value = unescape(pair[1])
else
value = name

this.params[name] = value

alert('QS Name = ' + name)
alert('QS Value = ' + value)

setCookie('AccountDetails.PromotionCode', value, '7')

}
}

function Querystring_get(key, default_) {
// This silly looking line changes UNDEFINED to NULL
if (default_ == null) default_ = null;

var value=this.params[key]
if (value==null) value=default_;

return value
}


</script>

The HTML


<INPUT class="formInputLarge" maxLength="35" size="50" name="AccountDetails.PromotionCode" id="AccountDetails.PromotionCode" style="MARGIN-TOP: 10px; MARGIN-BOTTOM: 10px" onload="this.value=getCookie(AccountDetails.PromotionCode)">

Thanks everyone, I'll keep my fingers crossed...