how to get single value by cookie in java script - javascript

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'));

Related

LocalStorage string always returning undefined JS

My localStorage string is always returning undefined, no matter what I do? I need help.
Related code snippets:
if (window.localStorage.firstVisit !== "false") {
window.localStorage.score = 0;
window.localStorage.name = "";
var origScore = parseInt(window.localStorage.score, 10);
window.localStorage.name;
} else {
var origScore = parseInt(window.localStorage.score, 10);
window.localStorage.name;
}
window.localStorage.firstVisit = "false";
var e = 0;
var fallenHuman = window.localStorage.name;
...
console.log(fallenHuman);
window.localStorage.name = fallenHuman;
var fallenHuman = window.localStorage.name;
document.getElementById("namesh").innerHTML = fallenHuman + " - Click to change";
From the looks of it, it looks like you are not using localStorage correctly. You are setting properties on the localStorage object, not actually in localStorage.
Secondly, you have something like this, which doesn't make any sense:
var fallenHuman = window.localStorage.name;
console.log(fallenHuman);
window.localStorage.name = fallenHuman;
You are just setting itself to ...itself. fallenHuman and window.localStorage.name are the exact same thing at all times. This code does nothing.
Example of working with localStorage from the docs
Sets an item in localStorage
localStorage.setItem('myCat', 'Tom');
Gets an item from localStorage
var cat = localStorage.getItem('myCat');
I've never actually seen anyone use localStorage in a way that you're using it, but I can assure you, that is not the intended usage of localStorage.
Unrelated your actual issue: you can probably drop window from all your code. You should be able to just do localStorage.* and be fine. I'm not sure what your setup is, so if that doesn't work, disregard this.

Use cookie to set link?

If cookies are used to stor simple strings can I also use the cookie to set the link of a button.
the idea: I have a simple HTML which i use to create a help file (this is very simple and I already have it), but we also make use of heaps of relating MSDS documents, so instead of me finding the thousands of documents online, i was thinking that Id get my users to set this by setting a cookie and ussing the cookies string to set the link ready for use the next time?
I can set read delete and modyfy cookies using Javascript...
Granted this function (http://www.w3schools.com/js/js_cookies.asp) to get the cookie item works, this should do the job:
var getCookie = function(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) {
return c.substring(name.length,c.length);
}
}
return "";
}
var click = function () {
window.location.href = getCookie('buttonUrl');
}
<button onclick="click()">See documentation</button>

Google Script to see if text contains a value

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');

Can't access fields of a Javascript Object

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] + '"');
}

Accessing CGI values with Prototype

Anyone know the quickest way to grab the value of a CGI variable in the current URL using Prototype? So if I get redirected to a page with the following URL:
http://mysite.com/content?x=foobar
I am interested in retrieving the value of "x" (should be "foobar") in a function called on page load like this:
Event.observe(window, "load", my_fxn ());
Thanks
You may want to look at the parseQuery method. This should do all the splitting you'd expect on a standard querystring such as document.location.search
http://api.prototypejs.org/language/string.html#parsequery-instance_method
For example:
document.location.search.parseQuery()["x"];
Will be undefined if it's not present, and should be the value otherwise.
I couldn't find any shortcuts here, so in the end I just parsed the URL with js like so:
function my_fxn () {
var varsFromUrl = document.location.search;
// get rid of first char '?'
varsFromUrl = varsFromUrl.substring(1);
var pairsArray = varsFromUrl.split("&");
for (i = 0; i < pairsArray.length; i++) {
var pair = pairsArray[i].split("=");
if (pair[0] == "x")
alert(pair[1] + ' is what I want.');
}
}

Categories