How do I check if a cookie exists? - javascript

What's a good way to check if a cookie exist?
Conditions:
Cookie exists if
cookie1=;cookie1=345534;
//or
cookie1=345534;cookie1=;
//or
cookie1=345534;
Cookie doesn't exist if
cookie=;
//or
<blank>

You can call the function getCookie with the name of the cookie you want, then check to see if it is = null.
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
// because unescape has been deprecated, replaced with decodeURI
//return unescape(dc.substring(begin + prefix.length, end));
return decodeURI(dc.substring(begin + prefix.length, end));
}
function doSomething() {
var myCookie = getCookie("MyCookie");
if (myCookie == null) {
// do cookie doesn't exist stuff;
}
else {
// do cookie exists stuff
}
}

I have crafted an alternative non-jQuery version:
document.cookie.match(/^(.*;)?\s*MyCookie\s*=\s*[^;]+(.*)?$/)
It only tests for cookie existence. A more complicated version can also return cookie value:
value_or_null = (document.cookie.match(/^(?:.*;)?\s*MyCookie\s*=\s*([^;]+)(?:.*)?$/)||[,null])[1]
Put your cookie name in in place of MyCookie.

document.cookie.indexOf('cookie_name=');
It will return -1 if that cookie does not exist.
p.s. Only drawback of it is (as mentioned in comments) that it will mistake if there is cookie set with such name: any_prefix_cookie_name
(Source)

This is an old question, but here's the approach I use ...
function getCookie(name) {
var match = document.cookie.match(RegExp('(?:^|;\\s*)' + name + '=([^;]*)'));
return match ? match[1] : null;
}
This returns null either when the cookie doesn't exist, or when it doesn't contain the requested name.
Otherwise, the value (of the requested name) is returned.
A cookie should never exist without a value -- because, in all fairness, what's the point of that? 😄
If it's no longer needed, it's best to just get rid of it all together.
function deleteCookie(name) {
document.cookie = name +"=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}

ATTENTION!
the chosen answer contains a bug (Jac's answer).
if you have more than one cookie (very likely..) and the cookie you are retrieving is the first on the list, it doesn't set the variable "end" and therefore it will return the entire string of characters following the "cookieName=" within the document.cookie string!
here is a revised version of that function:
function getCookie( name ) {
var dc,
prefix,
begin,
end;
dc = document.cookie;
prefix = name + "=";
begin = dc.indexOf("; " + prefix);
end = dc.length; // default to end of the string
// found, and not in first position
if (begin !== -1) {
// exclude the "; "
begin += 2;
} else {
//see if cookie is in first position
begin = dc.indexOf(prefix);
// not found at all or found as a portion of another cookie name
if (begin === -1 || begin !== 0 ) return null;
}
// if we find a ";" somewhere after the prefix position then "end" is that position,
// otherwise it defaults to the end of the string
if (dc.indexOf(";", begin) !== -1) {
end = dc.indexOf(";", begin);
}
return decodeURI(dc.substring(begin + prefix.length, end) ).replace(/\"/g, '');
}

If you're using jQuery, you can use the jquery.cookie plugin.
Getting the value for a particular cookie is done as follows:
$.cookie('MyCookie'); // Returns the cookie value

regexObject.test( String ) is faster than string.match( RegExp ).
The MDN site describes the format for document.cookie, and has an example regex to grab a cookie (document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");). Based on that, I'd go for this:
/^(.*;)?\s*cookie1\s*=/.test(document.cookie);
The question seems to ask for a solution which returns false when the cookie is set, but empty. In that case:
/^(.*;)?\s*cookie1\s*=\s*[^;]/.test(document.cookie);
Tests
function cookieExists(input) {return /^(.*;)?\s*cookie1\s*=/.test(input);}
function cookieExistsAndNotBlank(input) {return /^(.*;)?\s*cookie1\s*=\s*[^;]/.test(input);}
var testCases = ['cookie1=;cookie1=345534;', 'cookie1=345534;cookie1=;', 'cookie1=345534;', ' cookie1 = 345534; ', 'cookie1=;', 'cookie123=345534;', 'cookie=345534;', ''];
console.table(testCases.map(function(s){return {'Test String': s, 'cookieExists': cookieExists(s), 'cookieExistsAndNotBlank': cookieExistsAndNotBlank(s)}}));

Note that if a cookie is secure, you cannot check in client side for its existence using document.cookie (which all of the answers are using). Such cookie can be checked only at sever side.

instead of the cookie variable you would just use document.cookie.split...
var cookie = 'cookie1=s; cookie1=; cookie2=test';
var cookies = cookie.split('; ');
cookies.forEach(function(c){
if(c.match(/cookie1=.+/))
console.log(true);
});

There are several good answers here. I however prefer [1] not using a regular expression, and [2] using logic that is simple to read, and [3] to have a short function that [4] does not return true if the name is a substring of another cookie name . Lastly [5] we can't use a for each loop since a return doesn't break it.
function cookieExists(name) {
var cks = document.cookie.split(';');
for(i = 0; i < cks.length; i++)
if (cks[i].split('=')[0].trim() == name) return true;
}

function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
else{
var oneCookie = dc.indexOf(';', begin);
if(oneCookie == -1){
var end = dc.length;
}else{
var end = oneCookie;
}
return dc.substring(begin, end).replace(prefix,'');
}
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
var fixed = dc.substring(begin, end).replace(prefix,'');
}
// return decodeURI(dc.substring(begin + prefix.length, end));
return fixed;
}
Tried #jac function, got some trouble, here's how I edited his function.

For anyone using Node, I found a nice and simple solution with ES6 imports and the cookie module!
First install the cookie module (and save as a dependency):
npm install --save cookie
Then import and use:
import cookie from 'cookie';
let parsed = cookie.parse(document.cookie);
if('cookie1' in parsed)
console.log(parsed.cookie1);

Using Javascript:
function getCookie(name) {
let matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
}

Parse cookies with Array.prototype.reduce() into an object (ES6)
const cookies = document.cookie.split(";").reduce((e, t) => {
const [c, n] = t.trim().split("=").map(decodeURIComponent);
try { // this can be removed if you do not need JSON cookies parsed
return Object.assign(e, {
[c]: JSON.parse(n)
})
}
catch (t) {
return Object.assign(e, {
[c]: n
})
}
}, {})
Check if your cookie is there
typeof cookies.yourCookie === "string";

If anyone is still looking into this post maybe this will help.
First do a function to get the cookie, something like this..
function getCookie(cname) {
let name = cname + "=";
let ca = document.cookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Then you could check if the specific cookie exists before doing something else
if( getCookie(mycookieName)){
// do something....
}

// check if cookie is present
function is_CookiePresent( cookieName ){
if( void 0 != cookieName && "" != cookieName && null != cookieName ){
var is_present = document.cookie.split(";").filter(e=>{
if(e.trim().split("=").includes(cookieName)) return true;
})
if(!is_present.length){return false;}
return true;
}
else{
return false;
}
}
// Get cookie name value :)
function getCookieValue( cookieName ){
if( void 0 != cookieName && "" != cookieName && null != cookieName ){
var is_present = document.cookie.split(";").filter(e=>{
if(e.trim().split("=").includes(cookieName)) return true;
})
if(!is_present.length){return false;}
var __CookieValue = is_present.join('').trim();
return __CookieValue.substring(__CookieValue.indexOf('=')+1);
}
else{
return false;
}
}

use this method instead:
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
else return null;
}
function doSomething() {
var myCookie = getCookie("MyCookie");
if (myCookie == null) {
// do cookie doesn't exist stuff;
}
else {
// do cookie exists stuff
}
}

/// ************************************************ cookie_exists
/// global entry point, export to global namespace
/// <synopsis>
/// cookie_exists ( name );
///
/// <summary>
/// determines if a cookie with name exists
///
/// <param name="name">
/// string containing the name of the cookie to test for
// existence
///
/// <returns>
/// true, if the cookie exists; otherwise, false
///
/// <example>
/// if ( cookie_exists ( name ) );
/// {
/// // do something with the existing cookie
/// }
/// else
/// {
/// // cookies does not exist, do something else
/// }
function cookie_exists ( name )
{
var exists = false;
if ( document.cookie )
{
if ( document.cookie.length > 0 )
{
// trim name
if ( ( name = name.replace ( /^\s*/, "" ).length > 0 ) )
{
var cookies = document.cookie.split ( ";" );
var name_with_equal = name + "=";
for ( var i = 0; ( i < cookies.length ); i++ )
{
// trim cookie
var cookie = cookies [ i ].replace ( /^\s*/, "" );
if ( cookie.indexOf ( name_with_equal ) === 0 )
{
exists = true;
break;
}
}
}
}
}
return ( exists );
} // cookie_exists

function getcookie(name = '') {
let cookies = document.cookie;
let cookiestore = {};
cookies = cookies.split(";");
if (cookies[0] == "" && cookies[0][0] == undefined) {
return undefined;
}
cookies.forEach(function(cookie) {
cookie = cookie.split(/=(.+)/);
if (cookie[0].substr(0, 1) == ' ') {
cookie[0] = cookie[0].substr(1);
}
cookiestore[cookie[0]] = cookie[1];
});
return (name !== '' ? cookiestore[name] : cookiestore);
}
To get a object of cookies simply call getCookie()
To check if a cookie exists, do it like this:
if (!getcookie('myCookie')) {
console.log('myCookie does not exist.');
} else {
console.log('myCookie value is ' + getcookie('myCookie'));
}
Or just use a ternary operator.

function hasCookie(cookieName){
return document.cookie.split(';')
.map(entry => entry.split('='))
.some(([name, value]) => (name.trim() === cookieName) && !!value);
}
Note: The author wanted the function to return false if the cookie is empty i.e. cookie=; this is achieved with the && !!value condition. Remove it if you consider an empty cookie is still an existing cookie…

var cookie = 'cookie1=s; cookie1=; cookie2=test';
var cookies = cookie.split('; ');
cookies.forEach(function(c){
if(c.match(/cookie1=.+/))
console.log(true);
});

You can verify if a cookie exists and it has a defined value:
function getCookie(cookiename) {
if (typeof(cookiename) == 'string' && cookiename != '') {
const COOKIES = document.cookie.split(';');
for (i = 0; i < COOKIES.length; i++) {
if (COOKIES[i].trim().startsWith(cookiename)) {
return COOKIES[i].split('=')[1];
}
}
}
return null;
}
const COOKIE_EXAMPLE = getCookie('example');
if (COOKIE_EXAMPLE == 'stackoverflow') { ... }
// If is set a cookie named "example" with value "stackoverflow"
if (COOKIE_EXAMPLE != null) { ... }
// If is set a cookie named "example" ignoring the value
It will return null if cookie doesn't exists.

Related

Javascript issue with precedence

I have built this function to replace a group of characters in a string by a random value from another list within a function:
function replaceExpr(a) {
var expToReplace = 0
var newSent = a
while (expToReplace == 0) {
if (a.search("zx") == -1) {
expToReplace = 1
} else {
var startPos = a.search("zx");
startPos += 2;
var endPos = a.search("xz");
var b = a.substring(startPos, endPos);
var fn = window[b];
if (typeof fn === "function") var newWord = fn();
final = newSent.replace("zx" + b + "xz", newWord);
newSent = final
a = a.replace("zx" + b + "xz", "")
}
}
return final
}
function appearance() {
var list = [
"attractive",
"fit",
"handsome",
"plain",
"short",
"tall",
"skinny",
"well-built",
"unkempt",
"unattractive"
]
return list[Math.floor(Math.random() * list.length)];
}
function personality() {
var list = [
"aggresive",
"absent-minded",
"cautious",
"detached from the real world",
"easygoing",
"focused",
"honest",
"dishonest",
"polite",
"uncivilized"
]
return list[Math.floor(Math.random() * list.length)];
}
An example :
var a = replaceExpr("Theodor is a zxappearancexz man. He seems rather zxpersonalityxz.")
alert(a)
// Theodor is a unattractive man. He seems rather cautious.
Everything works perfectly with the function but I have an issue related to it. As you can see, there's one grammar mistake : it's written "a unattractive" where it should be "an unattractive".
There's a function I usually use to to fix the a\an issue which is :
var AvsAnSimple = (function (root) {
//by Eamon Nerbonne (from http://home.nerbonne.org/A-vs-An), Apache 2.0 license
// finds if a word needs a "a" or "an" before it
var dict = "2h.#2.a;i;&1.N;*4.a;e;i;o;/9.a;e;h1.o.i;l1./;n1.o.o;r1.e.s1./;01.8;12.1a;01.0;12.8;9;2.31.7;4.5.6.7.8.9.8a;0a.0;1;2;3;4;5;6;7;8;9;11; .22; .–.31; .42; .–.55; .,.h.k.m.62; .k.72; .–.82; .,.92; .–.8;<2.m1.d;o;=1.=1.E;#;A6;A1;A1.S;i1;r1;o.m1;a1;r1; .n1;d1;a1;l1;u1;c1.i1.a1.n;s1;t1;u1;r1;i1;a1;s.t1;h1;l1;e1;t1;e1.s;B2.h2.a1.i1;r1;a.á;o1.r1.d1. ;C3.a1.i1.s1.s.h4.a2.i1.s1;e.o1.i;l1.á;r1.o1.í;u2.i;r1.r1.a;o1.n1.g1.j;D7.a1.o1.q;i2.n1.a1.s;o1.t;u1.a1.l1.c;á1. ;ò;ù;ư;E7;U1;R.b1;o1;l1;i.m1;p1;e1;z.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.toString(36).length;
node.article = dict[offset] == "." ? "a" : "an";
dict = dict.substr(1 + offset);
for (var i = 0; i < kidCount; i++) {
var kid = node[dict[0]] = {}
dict = dict.substr(1);
fill(kid);
}
}
fill(root);
return {
raw: root,
//Usage example: AvsAnSimple.query("example")
//example returns: "an"
query: function (word) {
var node = root, sI = 0, result, c;
do {
c = word[sI++];
} while ('"‘’“”$\''.indexOf(c) >= 0);//also terminates on end-of-string "undefined".
while (1) {
result = node.article || result;
node = node[c];
if (!node) return result;
c = word[sI++] || " ";
}
}
};
})({})
Now, the problem is that I can't find a way to use this function in conjunction with the replaceExpr. The following obviously wouldn't work because of order precedence :
var a = replaceExpr("Theodor is " + AvsAnSimple(zxappearancexz) + "man. He seems rather " + AvsAnSimple(zxpersonalityxz).")
I just recently started learning javascript so my knowledge is rather limited. Any ideas how I could overcome this?
Thank you!
You could use a regular expression to optionally match the " a " or "an" before your word in the input string and store that matched portion in a variable using the String.match() function, then check if that " a " or " an " exists in your matched string, do the manipulations you need to do and store that manipulated string in a separate variable, then use String.replace() to find that previously matched string again, and replace it wit
your manipulated string. The regular expression you could use for this is /(\san?\s)?(zx\w*zx)/gm
See the regular expression here for more context.
Thank you Joseph! With your help I managed to find something that works by using your regular expression. Here's my function :
function replaceExpr(a) {
var nbExprToReplace = 1;
while (nbExprToReplace == 1) {
if (a.search("zx") == -1) {
nbExprToReplace = 0;
} else {
var currentGroup = a.match(/(\san?\s)?(zx\w*xz)/);
var exprToChange = currentGroup[2];
exprToChange = exprToChange.slice(2,-2);
var exprToChange = window[exprToChange];
if (typeof exprToChange !== "function") {
alert("the keyword is not a recognized function!");
break;
} else {
exprToChange = exprToChange();
var final = exprToChange
};
if (currentGroup[1] === undefined) {
} else {
var newArticle = AvsAnSimple.query(exprToChange);
final = newArticle.concat(" " + final)
};
a = a.replace(currentGroup[0], " " + final);
};
};
return a;
};

Check file name suffix if .js

I need to check if file name suffix is type JavaScript (JS files end with *.js)
for that I use the following code which works
var ext = aa.getName().substr(aa.getName().lastIndexOf('.') + 1);
Now the problem is that if the file is named file2.json I'm still getting true (it's return json)
My question is if there a better way to do it i.e. given any file name like
file1.xml, file2.js, file3.json or file4.html, it will return true just for file2.
I believe this can work
function check(str){
if(str.match(/(\w*)\.js$/) == null){
console.log('false');
return false;
}
else {
console.log('true');
return true;
}
}
check('file1.xml');
check('file2.js');
check('file3.json');
check('file4.html');
let isJS = function(filename) {
return /\.js$/i.test(filename)
}
console.log(isJS("asd.json")) // false;
console.log(isJS("asdjs")) // false;
console.log(isJS("asd.js")) // true;
console.log(isJS("asd.JS")) // true;
You could check if string ends with .js with the following function:
function isJavascriptFile(str) {
var regex = /\.js$/;
var match = str.match(regex);
return match !== null;
}
According to your code you would use it like this:
var name = aa.getName();
isJavascriptFile(name);
I think for this case better not using regex,
var arr = [
'file1.xml',
'file2.js',
'file3.json',
'file4.html'
];
for(var i=0, len=arr.length; i<len; i++){
if(returnExtension(arr[i]) == 'js') {
alert('Your file is: ' + arr[i])
}
}
function returnExtension(filename){
var a = filename.split(".");
if( a.length === 1 || ( a[0] === "" && a.length === 2 ) ) {
return "";
}
return a.pop();
}
my working example is here https://jsfiddle.net/gat8mx7y/
You've to modify your code a little bit, you're almost right:
funciton isJavascriptFile(fileName){
var ext = fileName.substr(fileName.lastIndexOf('.') + 1);
if(ext === 'js'){ return true; }
return false;
}
if(isJavascriptFile(aa.getName()) ) {
console.log("file is javascript");
}
//function GetJSName(){
var filename="sample.js";
var name = filename.split('.')[0];
alert(name);
//};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

JavaScript check if a cookie exists via Name

I am trying to do a simple IF statement to check if a specific Cookie exists:
I'm not looking to over complicate anything just something simple like
if (document.cookie.name("a") == -1 {
console.log("false");
else {
console.log("true");
}
What is this syntax for this?
first:
function getCookie(name) {
var cookies = '; ' + document.cookie;
var splitCookie = cookies.split('; ' + name + '=');
if (splitCookie.lenght == 2) return splitCookie.pop();
}
then you can use your if statement:
if (getCookie('a'))
console.log("false");
else
console.log("true");
should have work.
Maybe this can help (w3schools documentation about javascript cookies) :
https://www.w3schools.com/js/js_cookies.asp
At A Function to Get a Cookie
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
this could help you:
class Cookies {
static exists(name) {
return name && !!Cookies.get(name);
}
static set(name, value, expires = Date.now() + 8.64e+7, path = '/') {
document.cookie = `${name}=${value};expires=${expires};path=${path};`;
}
static get(name = null) {
const cookies = decodeURIComponent(document.cookie)
.split(/;\s?/)
.map(c => {
let [name, value] = c.split(/\s?=\s?/);
return {name, value};
})
;
return name
? cookies.filter(c => c.name === name).pop() || null
: cookies
;
}
}

How to Detect if Cookies Are Disabled on Microsoft Edge / Windows 10?

I have some code that works in every other browser, but not in Windows 10 / Microsoft Edge. Any ideas?
function areCookiesEnabled() {
// Quick test if browser has cookieEnabled host property
if (navigator.cookieEnabled) {
return true;
}
// Create cookie
document.cookie = "cookietest=1";
var ret = document.cookie.indexOf("cookietest=") !== -1;
// Delete cookie
document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT";
return ret;
}
if (areCookiesEnabled()) {
alert("Cookies are enabled!");
} else {
alert("Cookies are not enabled!");
}
Cookies are blocked in settings
Stack Overflow says that cookies are enabled
you can create a cookie and then test it i have small but very usefull library for that here by this you can do something like this
if(navigator.cookieEnabled||cookier.make("test","test",1))
//if one of these returns true {
if(cookier.parse("test))
//if test cookie is set
{
console.log("cookies are allowed");
}
}
I ended up finding a Cookie library that tests it the proper way, by actually creating a real cookie:
https://github.com/ScottHamper/Cookies
The method used is Cookies.enabled. Here's the section of code that the author used:
var testKey = 'cookies.js';
var areEnabled = Cookies.set(testKey, 1).get(testKey) === '1';
Cookies.expire(testKey);
return areEnabled;
I tried this inside the Win10/Edge dev tools and it worked for me.
If you don't want to include separate js then, you can update your function as below
function areCookiesEnabled() {
var cookieEnabled = navigator.cookieEnabled;
// When cookieEnabled flag is present and false then cookies are disabled.
if (cookieEnabled === false) {
return false;
}
var isIE = /*#cc_on!#*/false;
var isEdge = !isIE && !!window.StyleMedia;
// try to set a test cookie if we can't see any cookies and we're using
// either a browser that doesn't support navigator.cookieEnabled
// or IE / Edge (which always returns true for navigator.cookieEnabled)
if ((cookieEnabled === null || isIE || isEdge)) {
document.cookie = "testcookie=1";
if (GetCookieValue("testcookie") != "1") {
return false;
} else {
document.cookie = "testcookie=; expires=" + new Date(0).toUTCString();
}
}
return true;
}
// Get cookie value by passing the key.
function GetCookieValue(strKey) {
// split cookies by '; ', keep space as it is.
var arrCookies = document.cookie.split('; ');
for (var i = 0; i < arrCookies.length; i++) {
var keyValuePair = GetKeyValuePair(arrCookies[i]);
// Match the key.
if (keyValuePair.key === strKey) {
// return value of matched key.
return keyValuePair.value;
}
}
// Return an empty string if key is not present.
return "";
}
// Get key value pair from the cookie string.
function GetKeyValuePair(strCookie) {
// "=" is a valid character in a cookie value according to RFC6265, so cannot `split('=')`
var separatorIndex = strCookie.indexOf('=');
// IE omits the "=" when the cookie value is an empty string
separatorIndex = separatorIndex < 0 ? strCookie.length : separatorIndex;
var key = strCookie.substr(0, separatorIndex);
var decodedKey;
try {
decodedKey = decodeURIComponent(key);
} catch (e) {
}
return {
key: decodedKey,
value: strCookie.substr(separatorIndex + 1)
};
};
I had fixed this problem this way.

Object doesn't support this property or method in IE8 javascript

Everything works perfectly with modern browsers but for ie8 I get this error for this line:
tabValues.push(tabParams[i].split(attribute_anchor_separator));
Here the whole function:
function checkUrl()
{
if (original_url != window.location || first_url_check)
{
first_url_check = false;
url = window.location + '';
// if we need to load a specific combination
if (url.indexOf('#/') != -1)
{
// get the params to fill from a "normal" url
params = url.substring(url.indexOf('#') + 1, url.length);
tabParams = params.split('/');
tabValues = [];
if (tabParams[0] == '')
tabParams.shift();
for (var i in tabParams)
tabValues.push(tabParams[i].split(attribute_anchor_separator));
product_id = $('#product_page_product_id').val();
// fill html with values
$('.color_pick').removeClass('selected');
$('.color_pick').parent().parent().children().removeClass('selected');
count = 0;
for (var z in tabValues)
for (var a in attributesCombinations)
if (attributesCombinations[a]['group'] === decodeURIComponent(tabValues[z][0])
&& attributesCombinations[a]['attribute'] === tabValues[z][1])
{
count++;
// add class 'selected' to the selected color
$('#color_' + attributesCombinations[a]['id_attribute']).addClass('selected');
$('#color_' + attributesCombinations[a]['id_attribute']).parent().addClass('selected');
$('input:radio[value=' + attributesCombinations[a]['id_attribute'] + ']').attr('checked', true);
$('input[type=hidden][name=group_' + attributesCombinations[a]['id_attribute_group'] + ']').val(attributesCombinations[a]['id_attribute']);
$('select[name=group_' + attributesCombinations[a]['id_attribute_group'] + ']').val(attributesCombinations[a]['id_attribute']);
}
// find combination
if (count >= 0)
{
findCombination(false);
original_url = url;
return true;
}
// no combination found = removing attributes from url
else
window.location = url.substring(0, url.indexOf('#'));
}
}
return false;
}
Any ideas?? Thx!
I noticed you are using a for..in over an Array however using for..in was meant to be used for iteration over objects (not arrays):
for ( var prop in obj1 ) {
if ( obj1.hasOwnProperty(prop) ) {
// loop body goes here
}
}

Categories