George Brooks
George Brooks

Reputation: 199

JavaScript: setting a cookie not working

I would like to store user input from HTML input tags as a cookie to use later on. I need to read multiple input boxes and store the text values when a button is clicked by the user.

My problem is that saving the information to a cookie does not seem to be working correctly and instead saves no information, from what i can see using alert(document.cookie)

HTML Code:

<form id="contact-form">
    <label for="name">Log entry name:</label>
    <input type="text" id = "eName"  value="" placeholder="Run at the park"/>
    <label for="email">Name of exercise:</label>
    <input type="name" id = "exercise"  value="" placeholder="Jogging"  />
    <label for="telephone">Date: </label>
    <input type="number" id = "date" value="" />
    </form>

<li><a href="#" onclick ="setCookie()"> Add New Log</a></li>
<li><a href="#" onclick ="getCookie()"> cookie</a></li>

JavaScript:

<script type = "text/JavaScript">
function setCookie(){

var cookieString = "entry=" + document.getElementById("eName").value +
                    ";exercise=" + document.getElementById("exercise").value +
                    ";date=" + document.getElementById("date").value ;

document.cookie = cookieString;

}

function getCookie(){

alert(document.cookie);

}

when I show the cookie as an alert this is the response:

enter image description here New to javascript, so be gentle with me thank you and all help is appriciated.

Upvotes: 0

Views: 1264

Answers (1)

Koby Douek
Koby Douek

Reputation: 16693

Your cant read a cookie by using document.cookie.

In order to read a cookie, use this:

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

Upvotes: 2

Related Questions