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."
Related
Hi there I have the following code:
function showsaveobj(){
let patient = creatobj();
let befaktoren = patient.addfaktoren();
console.log(befaktoren);
let show = document.getElementById("show");
show.innerHTML = "Vorname: " + patient.vorname + "<br>Nachname: " + patient.nachname + "<br>" + (function() {for (let entry of befaktoren.entries()){return entry}})();
};
This last function is invoked when I press save inside the html document. It creates an object with a surname and a lastname and it has a method which creates a map out of the values the user has entered into the form. The form has 24 values corresponding to the 24h of the day. So the map is 24 entries long. I want to print these entries into the html document as you can see above. It works fine with the name and the surname but when I use the for..of loop to write the single entries It only prints out the first entry of the map.
When I add
for (let x of befaktoren.entries()){console.log(x);}
The console shows me 24 Arrays with the key and the value inside. When I do the same thing inside the string with innerHtml it only writes the first array of the map into the document.
I am doing something wrong here, but i cannot figure out what. After searching the web for several days now i hope someone here can help me.
Thanks in advance
I think you misunderstood the Map.entries() method. entries() does not return an iterable object that you can traverse with a for loop, but instead it returns an Iterator that contains all the entries which you can then retrieve with the next() method.
see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators
A Map itself is iterable so you can use your for loop on the map itself.
Despite that
your code:
someString + (function() {
for (let entry of befaktoren.entries()) {
return entry
}
})()
will always put the first element only into your string.
instead do something like this:
var befaktorenFormatter = function(input) {
let formattedString;
// directly iterate over the input iterable
for (let entry of input) {
formattedString += entry;
}
// don't return the current entry, return the fully formatted string instead
return formattedString;
}
show.innerHTML = "Vorname: " + patient.vorname + "<br>Nachname: " + patient.nachname + "<br>" + befaktorenFormatter(befaktoren);
Map has the convenience method forEach for iterating over its contents.
Also see: http://devdocs.io/javascript/global_objects/map/foreach .
Instead of using a for loop you could also do something like this:
let befaktoren = new Map([['foo', 'bar'], ['bar', 'foo']]);
let befaktorenFormatter = function(input) {
let formattedString;
input.forEach(function(value, key) {
formattedString += `${key}: ${value}<br>`;
});
return formattedString;
};
show.innerHTML = "Vorname: " + patient.vorname + "<br>Nachname: " + patient.nachname + "<br>" + befaktorenFormatter(befaktoren);
I hope that helped.
I am currently trying to retrieve the corresponding dial_code by using the name which I am obtaining as a variable.
The application uses a map of the world. When the user hovers over a particular country, that country is obtained using 'getRegionName'. This is then used to alter the variable name. How can I use the variable name to retrieve the dial_code that it relates to?
JSON
var dialCodes = [
{"name":"China","dial_code":"+86","code":"CN"},
{"name":"Afghanistan","dial_code":"+93","code":"AF"}
];
The following code runs on mouse hover of a country
var countryName = map.getRegionName(code);
label.html(name + ' (' + code.toString() + ')<br>' + dialCodes[0][countryName].dial_code);
This code doesn't work correctly. The dialCodes[0][countryName].dial_code is the part that is causing the error, but I'm not sure how to correctly refer to the corresponding key/value pair
If you have to support old browsers:
Loop over the entries in the array and compare to the given name:
var dialCode;
for(var i = 0; i < dialCodes.length; i++) {
if(dialCodes[i].name === countryName) {
dialCode = dialCodes[i].dial_code;
break;
}
}
label.html(countryName + ' (' + dialCode + ')');
If you browser support Array.prototype.filter:
dialCodes.filter(function(e) { return e.name === 'China' })[0].dial_code
If you have control over it, I recommend making your object more like a dictionary, for example if you are always looking up by the code (CN or AF) you could avoid looping if you did this:
var dialCodes = {
CN: { "name":"China","dial_code":"+86","code":"CN" },
AF: {"name":"Afghanistan","dial_code":"+93","code":"AF"}
};
var code = dialCodes.CN.dial_code;
Or
var myCode = 'CN'; // for example
var code = dialCodes[myCode].dial_code;
Since it's an array you can use filter to extract the data you need.
function getData(type, val) {
return dialCodes.filter(function (el) {
return el[type] === val;
})[0];
}
getData('code', 'CN').dial_code; // +86
I'm trying to save numbers given by Math.random. I save them in array which gets saved into localStorage. I then want to append each new array of numbers when Math.random is used. It's easier if you view the code I tried wrting.
var nums = [];
for (var i = 0; i < 5; i++) {
var num = Math.floor(Math.random() * 50);
nums.push(" " + num);
}
console.log(nums);
function appendToStorage(name, data) {
var old = localStorage.getItem(name);
if (old === null) old = "";
localStorage.setItem(name, old + JSON.stringify(data));
}
if (localStorage.num) {
appendToStorage('num', nums);
} else {
localStorage.setItem("num", JSON.stringify(nums));
}
var nums2 = localStorage.getItem("num");
console.log(nums2);
document.getElementById("test").innerHTML = JSON.parse(nums2);
This doesn't work, though. Console says Uncaught SyntaxError: Unexpected token [
This error will work if you remove the JSON.parse on getElementById. I want it to be parsed, though, so the numbers are more easily viewed. How can I do this?
If you simply append a valid JSON string to another valid JSON string you don't get a valid JSON string. For example:
var myJSON = '{"thing": "data"}'; // valid
myJSON = myJSON + myJSON; // myJSON is now '{"thing": "data"}{"thing": "data"}', not valid
To do this reliably you'll need to parse your retrieved JSON, update the result, then stringify it again before storing it in localStorage.
function appendToStorage(name, data) {
var old = localStorage.getItem(name);
if (old === null) old = "[]";
var newData = JSON.parse(old);
newData.push(data);
localStorage.setItem(name, JSON.stringify(newData));
}
Note that this will return an array when you parse it, and that will cause you a problem when you try to set innerHTML. You'll need to unpack the array to some sort of text format first (thanks to jibsales for that).
Element.innerHTML takes a string as valid input, not an Array. May I suggest using JSON.parse(nums).join("");
Using this method would also allow you to not add the leading white space in your for loop and instead add the white space as the first parameter to the Array.join method. If you want each number on a new line, pass "\n".
I have a problem to manipulate checkbox values. The ‘change’ event on checkboxes returns an object, in my case:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
The above object needed to be transformed in order the search engine to consume it like:
{ member,book,journal,new_member,cds}
I have done that with the below code block:
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr=[];
for (var i in value) {
arr.push(value[i])
};
var wrd = new Array(arr);
var joinwrd = wrd.join(",");
var filter = '{' + joinwrd + '}';
//console.log(filter);
//Ext.Msg.alert('Output', '{' + joinwrd + '}');
});
The problem is that I want to the “change” event’s output (“var filter” that is producing the: { member,book,journal,new_member,cds}) to use it elsewhere. I tried to make the whole event a variable (var output = “the change event”) but it doesn’t work.
Maybe it is a silly question but I am a newbie and I need a little help.
Thank you in advance,
Tom
Just pass filter to the function that will use it. You'd have to call it from inside the change handler anyway if you wanted something to happen:
formcheckbox.on('change', function(cb, value){
//...
var filter = "{" + arr.join(",") + "}";
useFilter(filter);
});
function useFilter(filter){
// use the `filter` var here
}
You could make filter a global variable and use it where ever you need it.
// global variable for the search filter
var filter = null;
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr = [],
i,
max;
// the order of the keys isn't guaranteed to be the same in a for(... in ...) loop
// if the order matters (as it looks like) better get them one by one by there names
for (i = 0, max = 5; i <= max; i++) {
arr.push(value["val" + i]);
}
// save the value in a global variable
filter = "{" + arr.join(",") + "}";
console.log(filter);
});
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] + '"');
}