Hi all. I'm a novice when it comes to Javascript, so please bear with me if I've done something stupid. I'm trying to make a script that I can use for buttons to increase or decrease a cookie's value by 1. I've tried changing numerous things in the scripts, but nothing has got it working (the scripts for getting and setting the cookie are all working fine).
Here are my scripts for setting and getting the cookie, respectively:
Code:<script type="text/javascript"> function getCookie(name) { var a = document.cookie; var begin = a.indexOf(name + "="); var end = (a.indexOf(";", begin) == -1) ? a.length : a.indexOf(";", begin); return unescape(a.substring((begin + (name.length + 1)), end));} </script>This is my function that I'm using to write on the page what the value of the cookie is:Code:<script type="text/javascript"> function setCookie(name, value, expires, path, domain, secure ) { if (!name || !value) {return 0;} document.cookie = name + "=" + value + ( (expires) ? ";expires=" + expires_date.toGMTString() : "" ) + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? ";secure" : ""); } </script>
And here the two scripts that seem to be the problem, the increase and decrease value scripts (yes, I do mean to have the <=4 and >=1 in there for the variable, since I'd like to restrict it to that range):Code:<script type="text/javascript"> function wrtCookie(name){ var x = getCookie(name) if (x==4) { var line ='Variable is 4' document.write(line);} else if (x==3) { var line ='Variable is 3' document.write(line);} else if (x==2) { var line ='Variable is 2' document.write(line);} else if (x==1) { var line ='Variable is 1' document.write(line);} else { document.write('Cookie is not working');} } </script>
Code:<script type="text/javascript"> function incCookie(name) { var z = getCookie(name) var j = z++ if (j<=4) { setCookie('test',j,'4','','/','','');} } </script>All of those scripts are in my head tag. This is what I have in the body of my page:Code:<script type="text/javascript"> function decCookie(name) { var z = getCookie(name) var j = z-- if (j>=1) { setCookie('test',j,'4','','/','','');} } </script>
Does anyone know what I'm doing wrong here? Any help would be greatly appreciated.Code:<body> <script type="text/javascript">wrtCookie('test');</script><br /> <a href="javascript:location.reload(true)" onClick="setCookie('test','4','','/','','');">Set to 4.</a><br /> <a href="javascript:location.reload(true)" onClick="incCookie('test');">Add 1</a><br /> <a href="javascript:location.reload(true)" onClick="decCookie('test');">Subtract 1</a><br /> </body>


Reply With Quote
Bookmarks