Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
197
rated 0 times [  198] [ 1]  / answers: 1 / hits: 30869  / 9 Years ago, sun, october 18, 2015, 12:00:00

I'm using the below code to check if a cookie exists with a certain value then do something.



$(document).ready(function() {
if (document.cookie.indexOf('samplename=itsvalue')== -1 ) {
alert(cookie);
}
});


It always displays the alert whether the cookie exists or not. What I'm doing wrong here?


More From » jquery

 Answers
14

Original response:



Unless you have a cookie with the key samplename=itsvalue, your code will always evaluate to true. If the key is samplename and the value is itsvalue, you should rewrite the check like this:



if (document.cookie.indexOf('samplename') == -1 ) {
alert(cookie);
}


This will tell you that the cookie does not exist.



To see if it does exist:



if (document.cookie.indexOf('samplename') > -1 ) {
alert(cookie exists);
}


Updating to better address this question:



What you are looking for in that check will always evaluate to true and throw the alert. Add the following function to your js and call it to check if your cookie exists.



function getCookie(name) {
var cookie = document.cookie;
var prefix = name + =;
var begin = cookie.indexOf(; + prefix);
if (begin == -1) {
begin = cookie.indexOf(prefix);
if (begin != 0) return null;
} else {
begin += 2;
var end = document.cookie.indexOf(;, begin);
if (end == -1) {
end = cookie.length;
}
}
return unescape(cookie.substring(begin + prefix.length, end));
}


You can then check your cookies with the following:



var myCookie = getCookie(samplename);

if (myCookie == null) {
alert(cookie does not exist);
} else {
alert(cookie exists);
}

[#64693] Thursday, October 15, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tiasavannahw

Total Points: 448
Total Questions: 122
Total Answers: 113

Location: Maldives
Member since Tue, Dec 21, 2021
2 Years ago
;