I have a getter to get the value from a cookie.
Now I have 2 cookies by the name shares=
and by the name obligations=
.
I want to make this getter only to get the values from the obligations cookie.
How do I do this? So the 'for' splits the data into separate values and puts it in an array.
function getCookie1() {
// What do I have to add here to look only in the "obligations=" cookie?
// Because now it searches all the cookies.
var elements = document.cookie.split('=');
var obligations= elements[1].split('%');
for (var i = 0; i < obligations.length - 1; i++) {
var tmp = obligations[i].split('$');
addProduct1(tmp[0], tmp[1], tmp[2], tmp[3]);
}
}
My solution is this:
This function uses the Underscorejs _.find-function. Returns undefined if cookie name doesn't exist
Just to add an "official" answer to this response, I'm copy/pasting the solution to set and retrieve cookies from MDN (here's the JSfiddle
In you particular case, you would use the following function
Note that i only replaced "test2" from the example, with "obligations".
always works well:
No requirements for jQuery or anything. Pure old good JavaScript.
If you just need to check if some cookie exist then simple do this:
if cookie logged=true exist, you will get 2, if not 1.
logged=true - change this to you cookie name=value, or just a name
I know it is an old question but I came across this problem too. Just for the record, There is a little API in developers mozilla web page.
Yoy can get any cookie by name using only JS. The code is also cleaner IMHO (except for the long line, that I'm sure you can easily fix).
As stated in the comments be aware that this method assumes that the key and value were encoded using encodeURIComponent(). Remove decode & encodeURIComponent() if the key and value of the cookie were not encoded.
I have done it this way. so that i get an object to access to separate the values.With this u can pass the cookie to the parent and then you can access your values by the keys like