Skip to content

Get a cookie value (javascript)

so I am new to Javascript and I am attempting to get a cookie value to keep track of a test.

I have six questions and when a question is finished I increment “counter” up 1 value, this way if the user loses connection while on question four the counter would be at four. Then when they reconnect I could get that counter number from the cookie and launch from question four, rather than restarting the user at question one.

Here is my cookie, counter being the number that stores the question number.

 document.cookie = "value1=" + one + ";value2" + two + ";value3=" + three + ";value4" + four + ";value5=" + five + ";value6=" + six + ";count=" + counter + ";expires=" + exp.toUTCString();

Here is my attempt in trying to figure out how the values are storing, I have tried looking for counter, “count”, “count=”, and “count=6”

function getCookie(cookieName) {
            var name = cookieName + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i].trim();
                if ((c.indexOf(i)) == (all the options listed above)) {
                    alert("found");
                }

            }
            return "undefined";
        }

I cannot figure out what is being stored where. Yes the array should be broken up per “;” via the split() in the cookie. And when I call an alert on each variable “i” in the loop I get values such as “counter=6”.

I am having trouble in actually specifying some sort of “if” statement to capture JUST the counter variable.

Thank you!

Answer

You’re not using indexOf correctly.

function getCookie(cookieName) {
    var name = cookieName + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if ((c.indexOf(name)) == 0) {
            alert("found");
            return c.substr(name.length);
        }

    }
    alert("not found");
    return null;
}