I have a function that takes a parameter(key) to retrieve it’s value from a cookie. I call that function anywhere that I need a specific bit of information. except everything comes back as Undefined.
//before $(document).ready();
var keyval = ""; //VARIABLE FOR PASSING COOKIE VALUE
var getCookieVal =function(c_name){
var cleanCookie = document.cookie.substr(0, document.cookie.indexOf("; __utma="));//REMOVES EXTRA INFORMATION
var cookieArr = cleanCookie.split(";");//MAKES AN ARRAY OF EACH PAIR
$.each(cookieArr, function(index, val){
var valArr = val.split("=");//SPLITS THE KEY VALUE PAIR INTO AN ARRAY
var key = valArr[0];
keyval = valArr[1];
if (key == c_name){
alert(keyval);//ALERTS CORRECT ANSWER
return keyval;
}
});
console.log(keyval);//RETURNS UNDEFINED
}
//IN ANOTHER FILE I CALL THE FUNCTION:
$(document).ready(function(){
getCookieVal("username");
alert(keyval);//RETURNS UNDEFINED
});
Anyone know what I did wrong or how I can get that value?
Here you go:
So you
return falseinside the if-branch (once you find the desired value) to break out of the$.eachloop. Then, you justreturn valuefrom thegetCookieValfunction.Note that there is no need to define a global
keyvalvariable here.