I am trying to write an html page for class that uses a drop down menu to allow users to pull up a list of relevant information. Unfortunately I am having trouble figuring out how to make the script call on the information in the array. The jsfiddle has the full html section, any help would be GREATLY appreciated.
Please bear in mind that I am not very good with terminology, so be as specific as possible. Especially regarding jQuery, our teacher didn't go over it much so it's a freaking mystery to me.
Also, I do plan on adding more information to the objects in the array, but until I get it working, I don't want to waste the time on something I might need to restructure.
http://jsfiddle.net/GamerGorman20/nw8Ln6ha/11/
var favWebComics = [
Goblins = {1: "www.goblinscomic.org"},
GirlGenious = {1: "www.girlgeniousonline.com"},
GrrlPower = {1: "www.grrlpowercomic.com"}
];
var myFunction = function() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
document.getElementById("web").innerHTML = favWebComics.x;
};
Again, the JSFiddle link has the full html, there are some unused items currently, but I do plan on adding more of them soon.
My next plan is to incorporate images into the objects, so a picture loads for each selection option. How would I manage that?
[ ] is used for arrays, which are indexed with numbers. If you want named properties, you should use an object, which uses { } for its literals:
var favWebComics = {
Goblins: "www.goblinscomic.org",
GirlGenious: "www.girlgeniousonline.com",
GrrlPower: "www.grrlpowercomic.com"
};
= is for assigning to variables, not specifying property names in an object.
Then you need to understand the difference between . and [] notation for accessing objects. .x means to look for a property literally named x, [x] means to use the value of x as the property name. See Dynamically access object property using variable.
So it should be:
document.getElementById("web").innerHTML = favWebComics[x];
your array is not structured correctly and an object would be better suited:
var favWebComics = {
Goblins : "www.goblinscomic.org",
GirlGenious : "www.girlgeniousonline.com",
GrrlPower : "www.grrlpowercomic.com"
};
then you should be able to access the properties as you intend
favWebComics.Goblins
favWebComics.GirlGenious
favWebComics.GrrlPower
Technically you were treating the array like a dictionary. if you're going to do that but still wanna add more information later you'll need to use brackets {} on the code.
var favWebComics = {
Goblins: ["www.goblinscomic.org"],
GirlGenious: ["www.girlgeniousonline.com"],
GrrlPower: ["www.grrlpowercomic.com"]
};
Also for javascript, as long as your searching key value stores, use braces [] for the call. Here's the working code below.
document.getElementById("web").innerHTML = favWebComics[x];
I have your solution, that displays:
the selected choice
the url
the images
Please check the fiddle.
http://jsfiddle.net/nw8Ln6ha/13/
Your object would be:
var favWebComics = {
Goblins : {url:"www.goblinscomic.org", img:"img1"},
GirlGenious : {url:"www.girlgeniousonline.com", img:"img2"},
GrrlPower : {url:"www.grrlpowercomic.com", img:"img3"}
};
Your display code:
document.getElementById("demo").innerHTML = "You selected: "+x+" "+ eval("favWebComics[\""+x+"\"].url")+" "+ eval("favWebComics[\""+x+"\"].img");
Related
I have the following code :
var games = ["game_1", "game_2","game_3"]
var players= [{name:"steve"},{name:"sparrow"},{name:"captain"}]
var incomingData= [{game_1:"basketball"},{game_2:"badminton"},{game_3:"pingpong"}]
//change format as shown below:
reformat=[ {name:"steve",game:"basketball"},{name:"steve",game:"badminton"},{name:"steve",game:"pingpong"}]
incomingData.map(incomingData=>{
games.map((game,i)=>{
players[i].game= incomingData.game
})
})
console.log(players) //[ { name: 'steve', game: undefined }, { name: sparrow', game: undefined }, { name: 'captain', game: undefined } ]
I am trying to learn about how to handle objects. I am getting undefined for the list of game inside the object. I understand this approach is wrong and would like to get some suggestions regarding how to go about changing the format to the required format.
incomingData.map((data, i) => {
players[i].game = data[ games[i] ];
});
You just need one loop.
This is what you need:
incomingData.map(data=>{
games.map((game,i)=>{
players[i].game=incomingData[i][games[i]]
})
})
You can play with it on jsfiddle.
So how does it work? Inside innermost function you already see all necessary data. All you need is to properly assing game attribute of i-th player. So you need to take i-th object from incomingData and then read attribute that is i-th element of games. So for instance for 0 element you want incomingData[0].game_1 that is equivalent to incomingData[0]["game_1"] and since "game_1" is dynamic you replace it with games[i] which leads to final incomingData[i][games[i]].
Note also that you have used formal parameter name of outer map with the same name as variable in scop effectively hiding it. You could access that hidden variable but simpler and cleaner is to give different name, hence renamed to data.
Surely it can be simplified as other users shown, my goal here was to simply fix assignment leading to undefined. Enough for learning fundamentals, for optimal code however see one loop receipt.
try this
var games = ["game_1", "game_2","game_3"]
var players= [{name:"steve"},{name:"sparrow"},{name:"captain"}]
var incomingData= [{game_1:"basketball"},{game_2:"badminton"},{game_3:"pingpong"}]
//change format as shown below:
var reformat=[ {name:"steve",game:"basketball"},{name:"steve",game:"badminton"},{name:"steve",game:"pingpong"}]
games.map((game,i)=>{
players[i].game= incomingData[i][game];
})
console.log(players)
}
I have a question regarding variables in Javascript.
When I assign a var to a ID I do it like this:
var x = document.getElementById("div_name");
But I would like to make a variable which consists of multiple 'divs'.
I thought this might work but I does not:
var x = document.getElementById("div_name"),document.getElementById("div_name2");
Can someone please help me find the right code syntax and explain why the syntax I tried is incorrect.
So, If you just want them as a list of div's you could do this:
var x = [document.getElementById("div_name"),document.getElementById("div_name2")];
Just wrap them up with [].
If your var should contain more than one object (div in your case), then you need to have more variable or, better, an array.
You can create yor array by using following code.
var x = [document.getElementById("div_name"), document.getElementById("div_name2")];
This is due to the fact that different DIVs in the DOM page are different objects...
There is no such variable that is defined as:
var x = somthing, somesthingElse
You need to chose a variable that can store a collection of "things". In your case the Array is an ideal choice:
var x = [document.getElementById("div_name"),document.getElementById("div_name2")];
The brackets at the beginning and end of the expression are the syntax to declare a variable.
In addition to using Array, you can also store your divs in an Object
var divs = {
div1: document.getElementById("div_name"),
div2: document.getElementById("div_name2")
};
Thus, you could give a convenient name to your divs, but still pass them around as you please:
divs.div1;
divs.div2;
Or loop through them like so:
for (div in divs) {
console.log(divs[div]);
};
In an application I am working on I need to get a list of the names of all applicationScope variable then I need to cycle through them and filter out the ones starting with a know string say $xyx. I thought that the applicationScope.keySet().
I'm using this code for starter:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
if (itr.hasNext()){
var str:String = itr.next();
dBar.info(str,"Value = ");
}
if I put the variable col in a viewScope it shows a list of all the keys. but when I run the script the values displayed in the dBar info are not the keys but some other information that I'm not sure where it comes from.
I should just be able to iterat through the list of keys, am I missing something?
This code is in the before page loads event
After some poking around and experimenting I got this to work:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
while (itr.hasNext()){
var str:Map.Entry = itr.next();
if (str.substring(0,9) == "$wfsLock_"){
//do stuff
}
}
so I'm now a happy camper.
Although your code works in SSJS, it is not correct (and that's why I don't like SSJS...).
The applicationScope is an implementation of the java.util.Map interface and the keySet() method returns a Set containing the keys in that Map. Every entry is (probably) a String (other data types like integers are actually also valid). The line
var str:Map.Entry = itr.next();
doesn't cast it to a Map.Entry: it doesn't really do anything: str remains a string.
The Map interface also has an entrySet() method that returns the entries (Map.Entry). You can use that to retrieve the key as well as the value:
var it = applicationScope.entrySet().iterator();
while (it.hasNext()) {
var entry = it.next();
print( entry.getKey() + " = " + entry.getValue() );
}
(in this code the print() line will use the toString() method of the key as well as the value to send information to the console)
I see from your code that you've installed my XPages Debug Toolbar. You can also use that to quickly check what's in the scopes and what the actual datatype is.
I'm saving user preferences using localStorage, like this:
choicesObject = { //put values in an object
"measure1" : $("#m1").is(':checked'),
"measure2" : $("#m2").is(':checked'),
"measure3" : $("#m3").is(':checked'),
"measure4" : $("#m4").is(':checked'),
"measure5" : $("#m5").is(':checked'),
"measure6" : $("#m6").is(':checked'),
"measure7" : $("#m7").is(':checked'),
"measure8" : $("#m8").is(':checked')
}
localStorage.setItem("choices", JSON.stringify(choicesObject));
Then I'm getting them back out like this:
retrieveChoices = localStorage.getItem("choices");
choicesObject = JSON.parse(retrieveChoices);
for(var i = 0;i<9 ;i++){
This nex t line is the problem:
ticked = choicesObject.measure+i;
It just doesn't work and I've tried using quotes and square brackets.
element = "#m" + i;
if(ticked==true){
$(element).prop('checked', true);
}
else{
$(element).prop('checked', false);
}
}
}
I want to loop though the measure properties and restore the checkbox elements.
I'm aware that even my object create is inefficient and I could use a for loop for that but I just don't know how to deal with object properties when it comes to looping because I don't get how you can do it without breaking the object.
At least that works and I can get data into and out of objects that get stored in localStorage, but this really simple issue has me stumped.
PS. Would
choicesObject = localStorage.getItem(JSON.parse("choices"));
be a better shorthand? Just thought this now whilst re-reading my question.
Edit: Thanks everyone. I got 3 correct answers so quickly! Amazing. Thanks so much. This site and its members amaze me every day and have revolutionised my coding!
I'm going to choose the correct answer as the one that also gave me the new shorthand for my parsing, but all of you gave me what i needed to know. I'm going to go see if I can answer some noob questions now!
Use
ticked = choicesObject["measure"+i];
EDIT: Your shorthand would not work, use instead:
choicesObject = JSON.parse(localStorage.getItem("choices"));
An object is just like a "dictionary" of values, so you can access a property either by doing myobject.propertyName or myobject["propertyname"]. They are equivalent.
In your case you just have to replace ticked = choicesObject.measure+i; with
ticked = choicesObject["measure"+i];
Also, consider using the var keyword when defining variables, each time you ommit it a new global variable will be created in the window object, that is the case for retrievedChoices and choicesObject. You can confirm this by accessing them via window["choicesObject"] or window.choicesObject or just choicesObject anywhere after that script has run.
Jquery Each Json Values Issue
This question is similar to above, but not the same before it gets marked duplicated.
After realasing how to use computed values i came across another issue.
In my javascript i have the following code:
var incidentWizard = ['page1.html','page2.html','page3.html'];
var magicWizard = ['page1.html','page2.html','page3.html'];
var loadedURL = 'page1.html';
The input to this function would be (true,'incident')
function(next,wizardname)
{
var WizSize = incidentWizard.length;
wizardName = [wizardName] + 'Wizard';
var wizardPOS = jQuery.inArray(loadedURL,incidentWizard);
And now i want to use the wizardname parameter to decide what array i am going to use...
Loader(incidentWizard[wizardPOS],true);
Ive also tried
Loader([incidentWizard][wizardPOS],true);
and
Loader([incidentWizard][wizardPOS],true);
Also the loader function just required the string value in the array at wizardPOS sorry for confusion
But when trying this i always end up with the outcome...
/incidentWizard
I know this is something to do with using computed values but i've tried reading about them and cant seem to solve this issue.
Basicly i want to use the computed value of wizardName to access an an array of that name.
Please help supports, looking forward to seeing many ways to do this!
On this line:
wizardName = [wizardName] + 'Wizard';
You are attempting to concatenate the string 'Wizard' to an Array with one string element "incident". I'm assuming you just want regular string concatenation:
wizardName = wizardName + 'Wizard';
However, now you only have a string, not an array instance. To fix that, change the way you define your *Wizard arrays to something like:
var wizardyThings = {
incidentWizard : ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then your function (which is missing a name as it stands), becomes:
function someMethod(next, wizardname) {
wizardName = wizardName + 'Wizard';
var wizSize = wizardyThings[wizardName].length;
var wizardPOS = jQuery.inArray(loadedURL, wizardyThings[wizardName]);
...
}
You can only access properties of objects that way. For global values, window[ name ] will work. For simple local variables it's just not possible at all. That is, if inside a function you've got
var something;
then there's no way to get at that variable if all you have is the string "something".
I would just put each array as a prop on an object:
var obj {
incidentWizard: ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then you can just do obj['incidentWizard'] or obj.incidentWizard this will return:
['page1.html','page2.html','page3.html']