user3456807
user3456807

Reputation:

New value for cookie appended

This javascript code

function writeCookie(CookieName, CookieValue, CookieDuration) {
    var expiration = new Date();
    var now = new Date();
    expiration.setTime(now.getTime() + (parseInt(CookieDuration) * 60000));
    document.cookie = CookieName + '=' + escape(CookieValue) + '; expires=' + expiration.toGMTString() +
        '; path=/';
}

function readCookie(CookieName) {
    if (document.cookie.length > 0) {
        var beginning = document.cookie.indexOf(CookieName + "=");
        if (beginning != -1) {
            beginning = beginning + CookieName.length + 1;
            var ending = document.cookie.indexOf(";", beginning);
            if (ending == -1) ending = document.cookie.length;
            return unescape(document.cookie.substring(beginning, ending));
        }
        else {
            return "";
        }
    }
    return "";
}
var before = readCookie('totali');
var after = before + 1;
writeCookie('totali', after, 43200);

Should read cookie 'totali', add "1" to its value and then rewrite the new value. The first time I run the code, cookie becomes "1", but the second time becomes "11", the third "111" and so on. What could be the problem?

Upvotes: 0

Views: 76

Answers (1)

helderdarocha
helderdarocha

Reputation: 23637

You are concatenating strings. Convert the value read from the cookie into a number before attempting to add it:

var after = parseInt(before) + 1;

But the problem is that the first time you read the cookie, the value is an empty string, and parseInt("") will be NaN. In this case, you have to check before you use it. This will assign 1 if the function returns an empty string, or the value stored in the cookie + 1 if not:

var after = (before.trim() == "") ? 1 : parseInt(before) + 1;

This assumes you never place anything other than a number in that totali cookie.

See http://jsfiddle.net/9rLZP/3/ (I changed the name of the cookie, so you can see the change without having to remove the previous cookie)

Upvotes: 1

Related Questions