The following Javascript function returns a JS object:
function getCookies() {
var result = {};
var cookie = {};
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
cookie = cookies[i].split('=');
result[cookie[0]] = cookie[1];
}
return result;
}
When I tried to access its fields the "easy" way, all I got was "undefined", eg:
var c = getCookies();
alert(c.a_cookie_name);
alert(c['a_cookie_name']);
The only way I could access the keys and values was iterating through the fields, eg:
for(cookieName in c){
alert(c[cookieName]);
}
The question is how to access the fields without iterating?
Thank you.
P.S. The keys and values do exist, I can see the object fields with console.log(getCookies()) in Chrome.
You are properly accessing fields the problem is that hte fields you're accessing don't exist. It' looks like the property named a_cookie_name simply doesn't exist on the object.
EDIT
Given that the Chrome console shows the properties as existing, one possibility to consider is there is white space in the names of the properties. This could explain the difference as the white space would be hard to see in the console. To test that out try the following. It will make the spaces a bit more visible if they are there
for (var cookieName in c) {
alert('"' + cookieName + '"="' + c[cookieName] + '"');
}
Related
I've stored cookie information in a dictionary to be recalled, but I am having trouble using the keys to find elements within the page. When I run the below code, the information gets stored from the cookie in the dictionary fine. I can output the dictionary information into the console and everything looks fine for that as well. When I try to use the key, the element cannot be found, but when I hardcode span variable with the element's id (as in var span = document.getElementById('bar');) it works fine. Initially, I thought it was a casting issue or something, so I tried String(key), but that didn't work either. Is it a type issue? An incorrect reference? Any help would be appreciated, thanks!
var dict = {};
function foo() {
//Break cookie into dictionary
var keyValuePairs = document.cookie.split(';');
for(var i = 0; i < keyValuePairs.length; i++) {
var name = keyValuePairs[i].substring(0, keyValuePairs[i].indexOf('='));
var value = keyValuePairs[i].substring(keyValuePairs[i].indexOf('=')+1);
dict[name] = value;
}
//Search for elements using key value
for (const [key, value] of Object.entries(dict)) {
var span = document.getElementById(key);
if(span) {
console.log("Element found named " + key);
} else {
console.log(key + " element not found.");
}
console.log(key, value);
}
}
Issue was unintentional inclusion of space character resulting from
.substring(0, keyValuePairs[i].indexOf('='));
I changed it to
.substring(1, keyValuePairs[i].indexOf('='));
and it worked fine. All keys now contain only the intended value instead off "' 'value."
java script code is store cookie
document.cookie = 'CookieName='+'grid';
i want to get CookieName value grid i haveto store many cookie but i get this one this cookie store at the first index in cookie
$( document ).ready(function() {
var CookieName=document.cookie;
if(CookieName =='grid')
{
$('#tab_b').hide();
$('#tab_a').show();
}
else {
$('#tab_a').hide();
$('#tab_b').show();
}
});
how to get CookieName value
I got the impression that you found the answer by Jay Blanchard too long, so I'll provide a shorter alternative. But first let me say something else. As a comment to Jay Blanchard's answer, you wrote:
thanks bro i have got it and very simple and short function check it var allcookies = document.cookie; cookiearray = allcookies.split(';'); name = cookiearray[0].split('=')[0]; value = cookiearray[0].split('=')[1];
However, I highly recommend you rethink that as this assumes CookieName is always the first cookie. (Someone might say "but I will somehow make sure it always is", but the point is, this is key/value, not array, so the approach is conceptually wrong and confusing, or as they say, bad practice).
Now, for the code:
var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)CookieName\s*\=\s*([^;]*).*$)|^.*$/, "$1");
This is something I have blantantly stolen from the MDN page on cookies which I highly recommend if you want to learn more about cookies.
I have written a small function (I could probably make this much more efficient, but I have used it for a long time) which should work for you:
function getCookieAttr(attribute) {
var attr = attribute + "="; // create an attribute string
var parts = document.cookie.split(';'); // split the cookie into parts
for(var i = 0; i <parts.length; i++) { // loop through the parts for each item
var item = parts[i];
while (item.charAt(0)==' ') { // account for spaces in the cookie
item = item.substring(1); // set the item
}
if (item.indexOf(attr) == 0) { // if the item matches the attribute
return item.substring(attr.length,item.length); // return the value
}
}
return "";
}
To use the function pass the attribute name:
document.cookie = "CookieName=grid";
console.log(getCookieAttr('CookieName'));
I've been having a hard time with cross browser compatibility and scrapping the dom.
I've added data analytics tracking to ecommerce transactions in order to grab the product and transaction amount for each purchase.
Initially I was using document.querySelectorAll('#someId')[0].textContent to get the product name and that was working fine for every browser except internet explorer.
It took some time to figure out that it was the .textContent part that was causing ie problems.
Yesterday I changed .textContent to .innerText. From looking inside analytics it seems that the issue has been resolved for ie but now Firefox is failing.
I was hoping to find a solution without writing an if statement to check for the functionality of .textContent or .innerText.
Is there a cross browser solution .getTheText?
If not what would be the best way around this? Is there a simple solution? (I ask given my knowledge and experience with scripting, which is limited)
** added following comments **
If this is my code block:
// build products object
var prods = [];
var brand = document.querySelectorAll('.txtStayRoomLocation');
var name = document.querySelectorAll('.txtStayRoomDescription');
var price = document.querySelectorAll('.txtStayRoomSplashPriceAmount');
for(var i = 0; i < brand.length; i++) {
//set granular vars
var prd = {};
//add to prd object
prd.brand = brand[i].innerText;
prd.name = name[i].innerText;
prd.price = price[i].innerText;
prd.quantity = window.session_context_vars.BookingContext.Booking.ReservationLineItems[i].ReservationCharges.length/2;;
//add to prods array
prods.push(prd);
}
Then if I understand the syntax from the comments and the question linked to in the comment, is this what I should do:
// build products object
var prods = [];
var brand = document.querySelectorAll('.txtStayRoomLocation');
var name = document.querySelectorAll('.txtStayRoomDescription');
var price = document.querySelectorAll('.txtStayRoomSplashPriceAmount');
for(var i = 0; i < brand.length; i++) {
//set granular vars
var prd = {};
//add to prd object
prd.brand = brand[i].textContent || brand[i].innerText;
prd.name = name[i].textContent || name[i].innerText;
prd.price = price[i].textContent || price[i].innerText;
prd.quantity = window.session_context_vars.BookingContext.Booking.ReservationLineItems[i].ReservationCharges.length/2;;
//add to prods array
prods.push(prd);
}
So using or with a double bar || assigns the first non null value?
Re: your edit, not quite. The way to access methods or properties on an object (eg a DOM element) is to use dot notation if you have the name itself, or square brackets in case of variables/expressions (also works with strings, as in obj["propName"], which is equivalent to obj.propName). You can also just test the property against one element and use that from there on:
// build products object
var prods = [];
var brand = document.querySelectorAll('.txtStayRoomLocation');
var name = document.querySelectorAll('.txtStayRoomDescription');
var price = document.querySelectorAll('.txtStayRoomSplashPriceAmount');
for(var i = 0; i < brand.length; i++) {
//set granular vars
var prd = {};
//add to prd object
var txtProp = ("innerText" in brand[i]) ? "innerText" : "textContent"; //added string quotes as per comments
prd.brand = brand[i][txtProp];
prd.name = name[i][txtProp];
prd.price = price[i][txtProp];
prd.quantity = window.session_context_vars.BookingContext.Booking.ReservationLineItems[i].ReservationCharges.length/2;;
//add to prods array
prods.push(prd);
}
Regarding the line:
var txtProp = (innerText in brand[i]) ? innerText : textContent;
The in keyword checks an object to access the property (syntax: var property in object). As for the question notation (I made an error earlier, using ||, the correct thing to use was a :),
var myVar = (prop in object) ? object[prop] : false;
As an expression, it basically evaluates the stuff before the ?, and if it's true, returns the expression before the :, else the one after. So the above is the same as / a shorthand for:
if(prop in object){
var myVar = object[prop];
}
else{
var myVar = false;
}
Since you are checking between two properties only and wanting to assign one or the other, the shortest way would indeed be:
var txtProp = brand[i].innerText || brand[i].textContent;
It would basically test the first property, and if it were false or undefined, it would use the second one. The only reason I (pedantically) avoid using this is because the first test of a || b would fail even if a existed but just had a value of 0, or an empty string (""), or was set to null.
I have a google form that when the user submits it will trigger my function to run which is creating a summary of what they submitted as a Google Doc. I know it can automatically send an email but I need it formatted in a way that my user can edit it later.
There are some check boxes on the form -- but the getResponse() is only populated with the items checked and I need it to show all possible choices. Then I will indicate somehow what was checked.
I can't find a way to see if a text contains a value.
Like in Java with a String, I could do either .contains("9th") or .indexOf("9th") >=0 and then I would know that the String contains 9th. How can I do this with google scripts? Looked all through documentation and I feel like it must be the easiest thing ever.
var grade = itemResponse.getResponse();
Need to see if grade contains 9th.
Google Apps Script is javascript, you can use all the string methods...
var grade = itemResponse.getResponse();
if(grade.indexOf("9th")>-1){do something }
You can find doc on many sites, this one for example.
Update 2020:
You can now use Modern ECMAScript syntax thanks to V8 Runtime.
You can use includes():
var grade = itemResponse.getResponse();
if(grade.includes("9th")){do something}
I had to add a .toString to the item in the values array. Without it, it would only match if the entire cell body matched the searchTerm.
function foo() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('spreadsheet-name');
var r = s.getRange('A:A');
var v = r.getValues();
var searchTerm = 'needle';
for(var i=v.length-1;i>=0;i--) {
if(v[0,i].toString().indexOf(searchTerm) > -1) {
// do something
}
}
};
I used the Google Apps Script method indexOf() and its results were wrong. So I wrote the small function Myindexof(), instead of indexOf:
function Myindexof(s,text)
{
var lengths = s.length;
var lengtht = text.length;
for (var i = 0;i < lengths - lengtht + 1;i++)
{
if (s.substring(i,lengtht + i) == text)
return i;
}
return -1;
}
var s = 'Hello!';
var text = 'llo';
if (Myindexof(s,text) > -1)
Logger.log('yes');
else
Logger.log('no');
I want to create a log function where I can insert variable names like this:
var a = '123',
b = 'abc';
log([a, b]);
And the result should look like this in the console.log
a: 123
b: abc
Get the value of the variable is no problems but how do I get the variable names? The function should be generic so I can't always assume that the scope is window.
so the argument is an array of variables? then no, there is no way to get the original variable name once it is passed that way. in the receiving end, they just look like:
["123","abc"];
and nothing more
you could provide the function the names of the variables and the scope they are in, like:
function log(arr,scope){
for(var i=0;i<arr.length;i++){
console.log(arr[i]+':'scope[arr[i]]);
}
}
however, this runs into the problem if you can give the scope also. there are a lot of issues of what this is in certain areas of code:
for nonstrict functions, this is window
for strict functions, this is undefined
for constructor functions, this is the constructed object
within an object literal, this is the immediate enclosing object
so you can't rely on passing this as a scope. unless you can provide the scope, this is another dead end.
if you pass them as an object, then you can iterate through the object and its "keys" and not the original variable names. however, this is more damage than cure in this case.
I know you want to save some keystrokes. Me too. However, I usually log the variable name and values much like others here have already suggested.
console.log({a:a, b:b});
If you really prefer the format that you already illustrated, then you can do it like this:
function log(o) {
var key;
for (key in o) {
console.log(key + ":", o[key]);
}
}
var a = '1243';
var b = 'qwre';
log({
a:a,
b:b
});
Either way, you'd need to include the variable name in your logging request if you want to see it. Like Gareth said, seeing the variable names from inside the called function is not an option.
Something like this would do what you're looking for:
function log(logDict) {
for (var item in logDict) {
console.log(item + ": " + logDict[item]);
}
}
function logSomeStuff() {
var dict = {};
dict.a = "123";
dict.b = "abc";
log(dict);
}
logSomeStuff();
Don't know if this would really work in JS... but you can use a Object, in which you can store the name and the value:
function MyLogObject(name, value) {
this.name = name;
this.value = value;
}
var log = [];
log.push(new MyLogObject('a', '123'));
log.push(new MyLogObject('b', 'abc'));
for each (var item in log) {
if (item.value != undefined)
alert(item.name + "/" + item.value);
}
Then you can loop thru this Object and you can get the name and the value
You can't access the variable names using an Array. What you could do is use objects or pass the variable names as a String:
var x = 7;
var y = 8;
function logVars(arr){
for(var i = 0; i < arr.length; i++){
alert(arr[i] + " = " + window[arr[i]]);
}
}
logVars(["x","y"]);
I had a somewhat similar problem, but for different reasons.
The best solution I could find was:
MyArray = ["zero","one","two","three","four","five"];
MyArray.name="MyArray";
So if:
x=MyArray.name;
Then:
X=="MyArray"
Like I said, it suited my needs, but not sure HOW this will work for you.
I feel silly that I even needed it, but I did.
test this.
var variableA="valor01"; <br>
var variableB="valor02";
var NamevariableA=eval('("variableA")');<br>
var NamevariableB=eval('("variableB")');<br>
console.log(NamevariableA,NamevariableB);
atte.
Manuel Retamozo Arrué