Cookie returns NaN with parseInt - javascript

When I am trying to get the Cookie "Gold" which is a currency for my game, it returns NaN. right now the cookie is named "gold" and has a value of 7238 (for me obviously as I saved that as a cookie on my comp)
function getCookie(cname){
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i= 0; i < ca.length; i++){
var c = ca[i];
while(c.charAt(0) == ' '){
c = c.substring(1);
}
if(c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
var gold;
function getGold() {
if(getCookie("gold") == null) {
gold = 0;
} else {
var sup = getCookie("gold");
var co = parseInt(sup, 10);
gold += co;
}
}
getGold();
This results is NaN which is not helping as it isn't saying where I went wrong, I can also give the function I use to save cookies which is as followed:
function saveCookies(cname, value) {
var d = new Date();
d.setTime(d.getTime() + (365 * 24 * 60 * 60 *1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + value + ";" + expires + ";path=/";
}
Then when some hooligan clicks the "Save" button one of the functions it performs is
saveCookies("gold", gold")
That concludes all the information I could possibly give unless you need the whole program, which can be located at matrix-hub.com/CodeCoins.php

This results is NaN which is not helping as it isn't saying where I went wrong
First of all change this line saveCookies("gold", gold") to saveCookies("gold",7238) here your first argument is cookie name that is gold and second one is cookie value that should be 7238 not "gold"
Secondly, when you set var gold; the value of gold is undefined. So in your code block when you go to the else block because getCookie("gold") == null condition is false, value of gold is still undefined
var gold;
function getGold() {
if(getCookie("gold") == null) {
gold = 0;
} else {
var sup = getCookie("gold");
var co = parseInt(sup, 10); //7238
// this is where you messed up, undefined = undefined + 7238
gold += co;
}
return gold; // also missed this return line
}
console.log(getGold()); // it is returning NaN
Actually with this line gold += co; what do you want to accomplish ?
if you set cookie value gold=7238 then this line gold += co; should return 14476?

Related

Cookie keeps defaulting to HttpOnly when not set to do so?

I am trying to add simple themes to my website. The script is supposed to create a theme cookie to see what theme is used and then apply the style. It used to work but now it gets set to httpOnly(meaning it cant be changed by JS even if it gets created by JS). It gets set to http only true even if I specifficaly try to set it to false which prevents me from changing it. Here is the code:
// Themes
var numOfThemes = 2;
var theme = 0;
// Standart getCookie function copied from w3schools
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
// This function sets the theme depending on the value inside the theme cookie (eg.: "theme=3")
function applyTheme() {
var cookie = parseInt(getCookie("theme"));
var hs = document.getElementsByTagName('style');
if(hs.length > 1);
for (var i=0, max=hs.length; i < max; i++) {
hs[i].parentNode.removeChild(hs[i]);
}
switch(cookie) {
case 0:
theme = 0;
break;
case 1:
theme = 1;
var style = document.createElement('style');
style.innerHTML = ``;
document.head.appendChild(style);
break;
//...
}
}
// This is supposed to set the cookie inside the browser. I tried adding HttpOnly=false; at the end but it doesn't change anything
function setTheme(theme) {
const d = new Date();
d.setTime(d.getTime() + (365*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = "theme=" + theme + ";" + expires + ";path=/;SameSite=Lax;";
}
// this is the function for switching the theme on a button click
function themeSwitch() {
var theme = + parseInt(getCookie("theme")) + 1;
if(theme > 4) {
theme = 0;
}
setTheme(theme);
}
applyTheme();

Average and Lowest and Highest Temperature - JavaScript

This calculator is designed to accept user input for the purpose of calculating and reporting average temperatures. I've got the it completed for the most part but I'm running into an issue where low temps that have a different amount of digits than the high, example: 9 and 10 or 95 and 110, the script is valuing the low temp higher than the high temp. Under neath is the javascript I'm using. Unfortunately I can't add a screenshot yet but the output response on entering a low of 9 and a high of 10 is:
Please enter a low temperature less than the high temperature.
(function(){
var temperatures = [];
var lowest = 150;
var highest = 0;
var lowestDate;
var highestDate;
var lAverage = 0;
var hAverage = 0;
var table = $('table');
function addTemps() {
'use strict';
var table = "<table><tr><th style='width:110px'>Date</th><th>Low Temperature</th><th>High Temperature</th></tr>";
var lTemp = $('lTemp').value;
var hTemp = $('hTemp').value;
if (((parseFloat(lTemp) != parseInt(lTemp, 10)) || isNaN(lTemp) ||
(parseFloat(hTemp) != parseInt(hTemp, 10)) || isNaN(hTemp)) ||
(lTemp > 150) || (hTemp < 0) || (lTemp>hTemp)) {
if ((parseFloat(lTemp) != parseInt(lTemp, 10)) || isNaN(lTemp)){
table += '<tr><td colspan="3">Please enter a number for low temperature.</td></tr></table>';
}
if ((parseFloat(hTemp) != parseInt(hTemp, 10)) || isNaN(hTemp)){
table += '<tr><td colspan="3">Please enter a number for high temperature.</td></tr></table>';
}
if ((lTemp > 150) || (hTemp < 0)) {
table += '<tr><td colspan="3">Please enter a number below 150 for low, or a number greater than 0 for high temperature.</td></tr></table>';
}
if (lTemp>hTemp) {
table += '<tr><td colspan="3">Please enter a low temperature less than the high temperature.</td></tr></table>';
}
$('output').innerHTML = table;
}
else {
lTemp = parseInt(lTemp);
hTemp = parseInt(hTemp);
var newDate = new Date((new Date().getTime())-(temperatures.length * 86400000));
temperatures.push([newDate,lTemp,hTemp]);
table = createTable(table);
$('output').innerHTML = table;
}
return false;
}
function init() {
'use strict';
$('theForm').onsubmit = addTemps;
}
function createTable(tbl){
lAverage=0; hAverage=0;
for (var i = 0; i<temperatures.length; i++) {
var date = ''+(temperatures[i][0].getMonth()+1)+"/"+temperatures[i][0].getDate()+"/"+temperatures[i][0].getFullYear();
var low = temperatures[i][1];
var high = temperatures[i][2];
tbl += '<tr><td>'+date+'</td><td style="text-align: right">'+low+'</td><td style="text-align: right">'+high+'</td></tr>';
if (low < lowest){
lowest = low;
lowestDate = date;
}
if (high > highest){
highest = high;
highestDate = date;
}
lAverage+=temperatures[i][1];
hAverage+=temperatures[i][2];
}
lAverage=(lAverage/temperatures.length).toFixed(1);
hAverage=(hAverage/temperatures.length).toFixed(1);
tbl+='<tr class="summaryRow"><td>Averages</td><td style="text-align: right">'+lAverage+'</td><td style="text-align: right">'+hAverage+'</td></tr>';
tbl+='<tr class="summaryRow"><td colspan="3">The lowest temperature of '+lowest+' occured on '+lowestDate+'.</tr>';
tbl+='<tr class="summaryRow"><td colspan="3">The highest temperature of '+highest+' occured on '+highestDate+'.</tr>';
tbl+='</table>';
return tbl;
}
function $(elementID){
if (typeof(elementID) == 'string') {
return document.getElementById(elementID);
}
}
window.onload = init;
})();
I'm assuming this is an error in the addTemps function with parseFloat or parseInt but I'm stuck on what to actually modify to avoid this issue.
Here are some thoughts. I could not test this code in repl.it, so it might have some rough edges.
If I correctly understand what this code is supposed to do..
Two main issues were:
You were comparing strings to numbers in several locations.
Your addTemps() function always returned false -- is this correct?
I actually don't remember how onSubmit works as I've not used JQuery or forms in ages.
Adjust the return value from addTemps appropriately, if I got that part mixed up.
Not technically wrong, but you can use "convenience variables" to cache calculations/conversions. They are essentially "free" in JS. This can make Code easier to read, and compiler doesn't have to keep re-doing the same calc.
(function(){
// could avoid "magic numbers" in code with:
var min_valid_hiTemp = 0;
var max_valid_loTemp = 150;
// initialize vars
var temperatures = [];
var lowest = 150; // max_valid_loTemp;
var highest = 0; // min_valid_hiTemp;
var lowestDate = '';
var highestDate = '';
var lAverage = 0;
var hAverage = 0;
var table = $('table');
function addTemps() {
'use strict';
var table = "<table><tr><th style='width:110px'>Date</th><th>Low Temperature</th><th>High Temperature</th></tr>";
var lTemp = $('lTemp').value;
var hTemp = $('hTemp').value;
// convenience variables
loTemp_float = parseFloat(lTemp);
loTemp_int = parseInt(lTemp, 10);
hiTemp_float = parseFloat(hTemp);
hiTemp_int = parseInt(hTemp, 10);
loTemp_isNAN = isNaN(lTemp);
hiTemp_isNAN = isNaN(hTemp);
// print error message if input was invalid
if ( (loTemp_float != loTemp_int) ||
(hiTemp_float != hiTemp_int) ||
loTemp_inNaN || hiTemp_isNan ||
(loTemp_int > hiTemp_int) ||
(loTemp_int > 150) ||
(hiTemp_int < 0)
){
if ((loTemp_float != loTemp_int) || loTemp_isNAN){
table += '<tr><td colspan="3">Please enter a number for low temperature.</td></tr></table>';
}
if ((hiTemp_float != hiTemp_int) || hiTemp_isNAN){
table += '<tr><td colspan="3">Please enter a number for high temperature.</td></tr></table>';
}
// uses "magic numbers"
if ((loTemp_int > 150) || (hiTemp_int < 0)) {
table += '<tr><td colspan="3">Please enter a number below 150 for low, or a number greater than 0 for high temperature.</td></tr></table>';
}
if (loTemp_int > hiTemp_int) {
table += '<tr><td colspan="3">Please enter a low temperature less than the high temperature.</td></tr></table>';
}
// don't call createTable() ?
$('output').innerHTML = table;
// shouldn't this block return false? - To not submit the form
return false
}
// input is valid: store the temperature data
else {
// not necessary now - we already have variables with this info: loTemp_int, hiTemp_int
// lTemp = parseInt(lTemp);
// hTemp = parseInt(hTemp);
// curious how the number of stored temps is related to the date..?
var newDate = new Date((new Date().getTime())-(temperatures.length * 86400000));
// just use the variables we already have
//temperatures.push([newDate, lTemp, hTemp]);
temperatures.push([newDate, loTemp_int, hiTemp_int]);
table = createTable(table);
$('output').innerHTML = table;
// shouldn't this block return true? - To submit the form
return true
}
// ?? No matter what, return false?
// I suspect you want to return false if input was invalid, and true if it was valid.
// if so, the return values should be inside the "if" and the "else" blocks.
// Not outside both blocks, as it is here.
//return false;
}
function init() {
'use strict';
$('theForm').onsubmit = addTemps;
}
function createTable(tbl){
lAverage=0;
hAverage=0;
for (var i = 0; i<temperatures.length; i++) {
var date = ''+(temperatures[i][0].getMonth()+1)+"/"+temperatures[i][0].getDate()+"/"+temperatures[i][0].getFullYear();
var low = temperatures[i][1];
var high = temperatures[i][2];
tbl += '<tr><td>'+date+'</td><td style="text-align: right">'+low+'</td><td style="text-align: right">'+high+'</td></tr>';
if (low < lowest){
lowest = low;
lowestDate = date;
}
if (high > highest){
highest = high;
highestDate = date;
}
// you already have variables "low" and "high" - may as well use them
// lAverage+=temperatures[i][1];
// hAverage+=temperatures[i][2];
lAverage += low;
hAverage += high;
}
lAverage=(lAverage/temperatures.length).toFixed(1);
hAverage=(hAverage/temperatures.length).toFixed(1);
tbl+='<tr class="summaryRow"><td>Averages</td><td style="text-align: right">'+lAverage+'</td><td style="text-align: right">'+hAverage+'</td></tr>';
tbl+='<tr class="summaryRow"><td colspan="3">The lowest temperature of '+lowest+' occured on '+lowestDate+'.</tr>';
tbl+='<tr class="summaryRow"><td colspan="3">The highest temperature of '+highest+' occured on '+highestDate+'.</tr>';
tbl+='</table>';
return tbl;
}
function $(elementID){
if (typeof(elementID) == 'string') {
return document.getElementById(elementID);
}
}
window.onload = init;
})();
I actually don't remember how onSubmit works as I've not used JQuery or forms in ages.
Adjust the return value from addTemps appropriately, if I got that part mixed up.
Here is a repl version, that also corrects a couple typos that exist in the above code.
note: none of the "print" statements will appear until you reply to the "add another temp" prompt with something other than y. So that part of the functionality is not perfect, but you can see that the main sticky points of the logic have been correctly addressed.
// could avoid "magic numbers" in code with:
var min_valid_hiTemp = 0;
var max_valid_loTemp = 150;
// initialize vars
var temperatures = [];
var lowest = 150; // max_valid_loTemp;
var highest = 0; // min_valid_hiTemp;
var lowestDate = '';
var highestDate = '';
var lAverage = 0;
var hAverage = 0;
// var table = $('table');
// non html version
var table = 'table\n';
function addTemps() {
'use strict';
var table = 'Date' + ' ' + 'Low Temperature' + ' ' + 'High Temperature' + '\n';
// var lTemp = $('lTemp').value;
// var hTemp = $('hTemp').value;
// non html version:
var lTemp = prompt('enter low temp');
var hTemp = prompt('enter high temp');
// convenience variables
var loTemp_float = parseFloat(lTemp);
var loTemp_int = parseInt(lTemp, 10);
var hiTemp_float = parseFloat(hTemp);
var hiTemp_int = parseInt(hTemp, 10);
var loTemp_isNAN = isNaN(lTemp);
var hiTemp_isNAN = isNaN(hTemp);
// print error message if input was invalid
if ( (loTemp_float != loTemp_int) ||
(hiTemp_float != hiTemp_int) ||
loTemp_isNAN || hiTemp_isNAN ||
(loTemp_int > hiTemp_int) ||
(loTemp_int > 150) ||
(hiTemp_int < 0)
){
if ((loTemp_float != loTemp_int) || loTemp_isNAN){
table += 'Please enter a number for low temperature.' + '\n';
}
if ((hiTemp_float != hiTemp_int) || hiTemp_isNAN){
table += 'Please enter a number for high temperature.' + '\n';
}
// uses "magic numbers"
if ((loTemp_int > 150) || (hiTemp_int < 0)) {
table += 'Please enter a number below 150 for low, or a number greater than 0 for high temperature.' + '\n';
}
if (loTemp_int > hiTemp_int) {
table += 'Please enter a low temperature less than the high temperature.' + '\n';
}
// does't call createTable() ?
// $('output').innerHTML = table;
// without html:
console.log(table);
console.log();
// shouldn't this block return false? - To not submit the form
return false
}
// input is valid: store the temperature data
else {
// curious how the number of stored temps is related to the date..?
var newDate = new Date((new Date().getTime()) - (temperatures.length * 86400000));
temperatures.push([newDate, loTemp_int, hiTemp_int]);
table = createTable(table);
//$('output').innerHTML = table;
// non html version
console.log(table);
console.log();
// shouldn't this block return true? - To submit the form
return true
}
// ?? No matter what, return false?
// I suspect you want to return false if input was invalid, and true if it was valid.
// if so, the return values should be inside the "if" and the "else" blocks.
// Not outside both blocks, as it is here.
//return false;
}
function init() {
'use strict';
//$('theForm').onsubmit = addTemps;
// non html / jquery version
if (addTemps()){
console.log("submitted");
}
else {
console.log('not submitted');
}
}
function createTable(tbl){
lAverage=0;
hAverage=0;
for (var i = 0; i< temperatures.length; i++) {
var date = '' + (temperatures[i][0].getMonth()+1) +
"/" + temperatures[i][0].getDate() +
"/" + temperatures[i][0].getFullYear();
var low = temperatures[i][1];
var high = temperatures[i][2];
tbl += date + '\t' + low + '\t\t\t' + high + '\n';
if (low < lowest){
lowest = low;
lowestDate = date;
}
if (high > highest){
highest = high;
highestDate = date;
}
lAverage += low;
hAverage += high;
}
lAverage = (lAverage/temperatures.length).toFixed(1);
hAverage = (hAverage/temperatures.length).toFixed(1);
tbl += 'Averages' + '\t' + lAverage + ' low, ' + '\t\t' + hAverage + ' high' + '\n';
tbl += 'The lowest temperature of ' + lowest + ' occured on ' + lowestDate +'.\n';
tbl += 'The highest temperature of ' + highest + ' occured on ' + highestDate+'.\n';
tbl += '\n';
return tbl;
}
// window.onload = init;
var addAnother = 'y'
while (addAnother == 'y') {
init();
addAnother = prompt('press "y" to add another');
}

Hide all content exception made when URL parameter is used

I want to hide my website content exception made when ?token_code=12345678 is used in URL. This is the code that's not working correctly, it hides website but never shows it:
I'm calling script by www.example.com/?authtoken=12345678
So when that parameter is included in URL it should show website. But it's not displaying it. It's only hiding it.
PS. I'm using cookies to remember "token" :)
HTML:
<body data-token="12345678"> </body>
JS:
//setCookie and readCookie
function SetCookie(e, t, n) {
var r = new Date;
var i = new Date;
if (n == null || n == 0) n = 1;
i.setTime(r.getTime() + 36e5 * 24 * n);
document.cookie = e + "=" + escape(t) + ";expires=" + i.toGMTString()
}
function ReadCookie(e) {
var t = " " + document.cookie;
var n = t.indexOf(" " + e + "=");
if (n == -1) n = t.indexOf(";" + e + "=");
if (n == -1 || e == "") return "";
var r = t.indexOf(";", n + 1);
if (r == -1) r = t.length;
return unescape(t.substring(n + e.length + 2, r))
}
function DeleteCookie(name) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
//capitalzies string
function capitalize(str) {
var first = str.charAt(0).toUpperCase();
str = str.replace(/^.{1}/, first);
return str;
}
// get's the GET paramters like so --> $_GET('var1');
function getVar(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return (false);
}
// Checks for one of TWO access short codes
// includeOnly && excludeOnly
// If includeOnly is not NULL, then ONLY include
// categories mentioned in that varaible.
// Also, cookie the data, that it's saved.
// Of course, if anyone re-visits the site, and
// re-writes the GET paramter, it'd delete all
// previous data in the cookie.
var token_code = ["authtoken", "excludeOnly"];
var asc = ""; //this is used to select the CURRENT access short code
var tokenValues = [];
//first check if there are ANY get params.
if (getVar(token_code[0]) != false) {
//before writing the inlcude only, delete EXCLUDE only
DeleteCookie(token_code[1]);
SetCookie(token_code[0], getVar(token_code[0]));
}
if (getVar(token_code[1]) != false) {
//before writing the EXCLUDE only, delete include only
DeleteCookie(token_code[0]);
SetCookie(token_code[1], getVar(token_code[1]));
}
//Try and reaad the cookie (there should be a cookie named "includeOnly" or "excludeOnly -- both from token_code)
//includeOnly is present?
if (ReadCookie(token_code[0]).toString().length > 0) {
//defines what the user wants to do. Exlcude or include? when token_code[0] it's include!
asc = token_code[0];
var tokens = ReadCookie(asc).toString();
tokenValues = decodeURIComponent(tokens).split(',');
//loop through each category.
//hide every category and it's children
$("[data-token]").hide();
$.each(tokenValues, function (index, value) {
//show every category, and it's childen, for the values
$("[data-token='" + value + "']").show();
});
}
//excludeOnly is present?
if (ReadCookie(token_code[1]).toString().length > 0) {
//defines what the user wants to do. Exlcude or include? when token_code[0] it's include!
asc = token_code[1];
var tokens = ReadCookie(asc).toString();
tokenValues = decodeURIComponent(tokens).split(',');
//loop through each category.
//hide every category and it's children
$("[data-token]").show();
$.each(tokenValues, function (index, value) {
//show every category, and it's childen, for the values
$("[data-token='" + value + "']").hide();
});
}
is there an easier way to do this?
In the bottom of your code, were the comment says to show, it runs .hide().
Could that be a problem?
//show every category, and it's childen, for the values
$("[data-token='" + value + "']").hide();

any sort of getElement(s)By---- function for getting a class by name, returns undefined

function getElsByClass(searchClass,node) {
if ( node == null )
node = document;
var classElements = [],
els = node.getElementsByTagName("div"),
elsLen = els.length,
pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
function getSong() {
console.log("getSong ran");
var songN = getElsByClass("info")[0], nmSong = getCookie();
console.log(songN);
songN = songN.getElementsByTagName("a");
songN = songN[0].innerText + " - " + songN[1].innerText;
if (nmSong != songN) {
setCookie(songN);
} else {
setCookie(songN);
}
sendSong(songN);
return songN;
}
setInterval(getSong(), 10000);
I've tried songN = document.getElemenetsByClassName("info"), and every combination I could find, and it will only run for maybe 30 seconds before it closes, I need it to run for hours, unattended...
I can run
var songN = getElsByClass("info")[0];
console.log(songN); //is actually defined when ran in Javascript Console in Chrome..
songN = songN.getElementsByTagName("a");
songN = songN[0].innerText + " - " + songN[1].innerText;
in Javascript console, and it returns exactly, what I'm trying to do, but if it runs as a userscript or after it's been injected into the web page, I get Uncaught TypeError: Cannot read property 'getElementsByTagName' of undefined, and I've tried to define it many different ways I found through searching google, and stackoverflow, I've ran the script on window.load, in the <head>, and tried to make it run in <body>.
getElsByClass() is my last attempt at it, it's not actually apart of my script, just a bit I tried from another script, tried shortening the name so it couldn't possibly conflict, but still nothing.
=== Update ===
Here is some more of the code..
function getCookie() {
console.log("getCookie ran");
var sname = "songname=", ca = document.cookie.split(';'), i = 0, c, t;
for (i; i < ca.length; i++) {
c = ca[i].trim();
if (c.indexOf(sname) == 0) {
t = c.substring(sname.length, c.length);
console.log(t);
return t;
}
}
return "";
}
function setCookie(cvalue) {
console.log("setCookie ran");
var d = new Date();
d.setTime(d.getTime() + 210000);//set it to expire in 3 minutes and 30 seconds from current time (this is average song time.)
document.cookie = "songname=" + cvalue + "; expires=" + d.toGMTString();
}

Handling a single cookie containing selected checkboxes

I am building html pages with a lot of checkboxes. I want to manage a single cookie containing selected items. Cookie looks like 1234^9876^3456^ where ^ is the separator.
When the user checks or unchecks the box, the cookie shows the added or removed id number.
Here are the functions I am using. All but the 2 last are from know third-party developers. Some problems are:
Each checkbox has an onclick event AddRemoveOrdinal2(...);
The user sees okay checked and unchecked summary data, even refreshing the page but several cookies are stored in browser, same name, path, different content;
The last function RemoveOrdinal is used to remove an item from the summary, it deletes the cookie and does not replace the new one.
Maybe it would be better to start again with a new idea/procedure
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.toUTCString());
}
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function del_cookie(name)
{
if (dbug) alert('del_cookie');
document.cookie = name + '=' + '; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/; '
}
function get_cookie(name) {
if (dbug) alert('get_cookie');
var dcookie = document.cookie;
var cname = name + "=";
var clen = dcookie.length;
var cbegin = 0;
while (cbegin < clen) {
var vbegin = cbegin + cname.length;
if (dcookie.substring(cbegin, vbegin) == cname) {
var vend = dcookie.indexOf (";", vbegin);
if (vend == -1) vend = clen;
return unescape(dcookie.substring(vbegin, vend));
}
cbegin = dcookie.indexOf(" ", cbegin) + 1;
if (cbegin == 0) break;
} return null;
}
function set_array(name, ary, expires) {
if (dbug) alert('set_array');
var value = '';
for (var i = 1; ary[i]; i++) {
value += ary[i] + '^';
}
set_cookie(name, value, expires);
}
function AddRemoveOrdinal2(id, ordinal, id_checkbox){
var foo = document.getElementById(id_checkbox).checked;
if (foo == false) {
get_array(cookieName, myarray);
var myarray2 = init_array();
for (var i=0; i<next_entry(myarray); i++) {
if(myarray[i] != ordinal){
myarray2.push(myarray[i]);
}
}
del_cookie(cookieName);
set_array(cookieName, myarray2, expires);
myarray = myarray2;
// Code here to display:none/block
}
else {
get_array(cookieName, myarray);
myarray.push(ordinal);
set_array(cookieName, myarray, expires);
}
get_array(cookieName, myarray);
if(myarray.length > 1){
// Code here to display:none/block elements
}
else {
// Code here to display:none/block elements
}
function RemoveOrdinal(id, ordinal, id_checkbox){
get_array(cookieName, myarray);
var myarray2 = init_array();
for (var i=0; i<next_entry(myarray); i++) {
if(myarray[i] != ordinal){
myarray2.push(myarray[i]);
}
}
del_cookie(cookieName);
set_array(cookieName, myarray2, expires);
myarray = myarray2;
esconder(id);
document.getElementById(id_checkbox).checked=false;
get_array(cookieName, myarray);
if(myarray.length > 1){
// Code here to display:none/block elements
else {
// Code here to display:none/block elements
}
}
On load
var cookieName = 'ordinals';
var myarray = init_array();
var timeToKeep = 60000*60*24*7;
var expires = new Date();
expires.setTime(expires.getTime() + timeToKeep);
var x = get_cookie(cookieName);
if ( !x || x == null) {
set_array(cookieName, myarray, expires);
}

Categories

Resources