Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
var info = [
{'user': 'person1','location': "NY"},
{'user': 'person2','location': "NJ"},
{'user': 'person3','location': "NC"}
];
var text="";
for (var i=0; i<=2; i++) {
text+='<div id="box" onclick="alertMe()">'+ info </div>';
}
function alertMe(){
var val = info[location];
alert(val);
}
This is focused on the function alertMe() part. I'm trying to put each location in one variable so when the user clicks on one, it will show an alert with the specific location.
There is a few things that are not going to work with your code.
The variable location is not defined.
If you are trying to access the property location or your object, it might not work that way because info is an array. You could access info like so info[0] but not via the key location since it does not exist.
From what I undestand, you want to show the currently clicked location. Your alertMe function has no way to know which location has been clicked.
Not a problem but a suggestion, you might want to use let or const rather than val, here is why.
You are never adding your HTML string to the DOM, so nothing is appearing.
You are missing a ' in your string.
You are trying to show the variable info in the tag div in your html, yet info is an array of objects.
With that in mind, here is a revised version of your code. Please try to understand what's going on rather than copy pasting this into your project.
var info = [
{'user': 'person1','location': "NY"},
{'user': 'person2','location': "NJ"},
{'user': 'person3','location': "NC"}
];
let text = "";
for (var i=0; i<=2; i++) {
const currentLocation = info[i];
text+= `<div id="box" onclick="alertMe(${i})">${currentLocation.location}</div>`;
}
document.write(text)
function alertMe(index){
const val = info[index].location;
alert(val);
}
In this snippet, you can see that i've replace a few things.
The alertMe function now take an index as an argument. Which will represent the index being clicked.
I'm creating a new variable in my for loop for the current info element.
I'm using this new variable to print the location.
I'm accessing the clicked location via it's index rather than the innexisting location variable.
I've replaced your string building with string template. Not necessary but cool.
It doesn't work, because you're trying to access a property of an object in an array.
if you had:
const info = {'user': 'person1','location': "NY"}
then info['location'] would work.
The way you have it you need to point to the relevant item of the array first:
var info = [
{'user': 'person1','location': "NY"},
{'user': 'person2','location': "NJ"},
{'user': 'person3','location': "NC"}
];
let myLocation = info[0]['location']
where 0 is the index of tfirst element of the array.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 months ago.
Improve this question
edit: Below is a simplified version of what I tried to do. I apologize that it seemed incomplete. I tried to make a minimal reproducible example but my javascript knowledge is too lacking and I thought the problem was equivalent (trivial).
I have an array of endpoints choices.
I try to populate a dictionary data_collection.
choices.forEach((choice) => getAllData(choice.value))
where
function getAllData(datapoint)
{
d3.json(dataroot + datapoint).then((res) => alldata[datapoint] = res);
}
I get an error:
Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'Object'
I am now trying all the kind suggestions in the comments and will update as soon as I did all of them.
I've been trying to populate a "dictionary" of data in javascript and index it with a string.
I followed some simple guide but I must misunderstand it.
let choices = ["hello", "world", "yeah"]
let data_collection = new Object();
choices.forEach(choice => data_collection[choice] = choice.length);
console.log(data_collection);
I get an error of the sort object can't be assigned by string.
Many thanks in advance! Apologies for the absolute newbie question.
I don't know if this is the solution you are looking for, try it.
let choices = ["hello", "world", "yeah"]
let data_collection = new Object();
for (let i of choices) {
data_collection[choices.indexOf(i)] = i;
}
console.log(data_collection);
will display this in the console:
{0: 'hello', 1: 'world', 2: 'yeah'}
In Typescript, I'd say declare your dictionary properly as a Map, like
change
let choices = ["hello", "world", "yeah"]
let data_collection = new Object();
choices.forEach(choice => data_collection[choice] = choice.length);
console.log(data_collection);
into
let choices = ["hello", "world", "yeah"]
let data_collection: Map<string,number> = new Map<string,number>();
choices.forEach(choice => data_collection.set(choice, choice.length);
console.log(data_collection);
Testing above second fragment, my webkit console output for data_collection looks like this,
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to get Javascript Array to display each group name and group ID on its own line instead of sending the whole array to the next script. Essentially what would be desired is that the group ID and Group Name gets pushed "foreach" to the next script that will use those ids to generate a tab. I have the tab generation done and the data import done, the only thing I cant figure out is how to get the array to display each item separately.
Here is my current code:
$.getJSON("inc/load.php", function(data){
for (var i = 0, len = data.length; i < len; i++) {
var Names = data.group_name[i];
var GroupID = data.group_id[i];
console.log(Names + " " + GroupID)
}
I have searched on here and google and have not found a solution.
EDIT
The data does load information correctly, when you use
console.log(data[i]); it returns this style information in the console log:
Object {group_id: "556336557801913", group_name: "How to Start a Startup"}
Object {group_id: "1448816275428542", group_name: "ARK: Survival Evolved"}
Object {group_id: "286255764917755", group_name: "VIP BUYER ADVANTAGE MEMBER"}
What I would like the end result to be is to take the Group_Id and the Group_name put each into its own variable and then pass those variables to another function. And then repeat for the next item in the array.
Im sorry I am still new to Stackoverflow and learning how to best construct my questions.
Edit:
Rather than using for-in as Paul Rob rightly pointed out, you might just correct the following in your code for a start and that might sort you out.
var Names = data[i].group_name;
var GroupID = data[i].group_id;
End Edit
I think what you want is:
for (var i in data) {
var Names = data[i].group_name;
var GroupID = data[i].group_id;
console.log(Names + " " + GroupID);
}
Don't ask me why i is the index rather than the item, one of those nuances of javascript you just grow to live with and love :)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to map a user defined key to the associated value and it is currently returning undefined for the final (var final). The goal is to collect a user provided input (key) and map it to the associated string from the key:value object and then load a URL using this value. The web page loads incorrectly in the end because the value is undefined. Here is the code:
document.getElementById("btn").onclick = function onLoad() {
var converts = {
'apples' : 'green',
'sky' : 'blue'
};
var myTextField = document.getElementById("myTextarea");
var itemName = myTextField.value;
var final = converts[itemName];
if (document.getElementById('rad1').checked) {
window.open("somewebsite" + final + "restofURL", "this is a new window");
}
}
The problem is that the textarea has a lot of white-spaces in it by default. If the user adds a space, that could cause problems so we need to trim the string:
convert[ itemName.trim() ];
This will remove all the bordering whitespace.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am having a problem trying to change some innerHtml with this piece of code bellow:
var element = document.getElementByClass("productitemcell > a");
element.innerHTML = "Remover";
It is suposed to change the innerHTML from a link that says"Remove" to "Remover" and its not working.
Here's the page of it: http://ooleiro.businesscatalyst.com/OrderRetrievev2.aspx
You have to buy some products to access this shopping cart page.
I think you meant document.getElementsByClassName()
This method will return a HTMLCollection object. You can grab the first element like so:
var elements = document.getElementsByClassName('class');
var firstElement = elements[0];
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
The method is called getElementsByClassName (plural) and returns a collection of HTML elements. For which one of those do you want to change the HTML? For the first one?
Additionally, you cannot use a CSS selector like that in standard DOM methods
EDIT: Obviously you want to change all occurrences of a elements inside all occurrences of .productitemcell:
var pics = document.getElementsByClassName("productitemcell");
for(i=0; i<pics.length; i++) {
// loop over all elements with that class
var anchors = pics[i].getElementsByTagName("a");
for(j=0; j<anchors.length; j++) {
// loop over all anchor elements within the current class element
anchors[j].innerHTML = 'Remover';
}
}
Had to change the class to
var removerprod = document.getElementsByClassName("remover");
for(i=0; i<removerprod.length; i++) {
// loop over all elements with that class
var anchors = removerprod[i].getElementsByTagName("a");
for(j=0; j<anchors.length; j++) {
// loop over all anchor elements within the current class element
anchors[j].innerHTML = 'Remover';
}
}
so it doesnt change the product name as well. the only problem remaining is that it is retrieving with ajax and everytime it refreshes it changes again to "Remove"Thank's you devnul69, i realy learned a lot today about js.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I had a object object array which i used JSON.stringify() on i can now see what's in my array but when i do arr[0] etc it only outputs one letter.
arr = {"hello":"yes","because":"no"}
arr[0] =h
I want it to output the whole of the value not just the first letter
My code
var clientContext = SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
// Get user properties for the target user.
// To get the PersonProperties object for the current user, use the
// getMyProperties method.
MyProperties = peopleManager.getMyProperties();
// Load the PersonProperties object and send the request.
clientContext.load(MyProperties);
clientContext.executeQueryAsync(getMyNewsChoicesSuccess, getMyNewsChoicesFail);
},
getMyNewsChoicesSuccess = function () {
//get the news choice by actually fieldname
var MyChoices = JSON.stringify(MyProperties.get_userProfileProperties().Value);
$('#NBStest').text(MyChoices);
},
You can get the first element from your json string like this
JSON.parse(json_str)[0]
but in the example you have, the first element is "yes" and its index is "hello" , which means you can't get the first element by the index 0 , however you can get it by its property name like this
arr.hello = "yes";
// or
arr['hello'] = "yes";
if you want to get the hello which is the key , you have to use this loop
for (key in arr)
console.log(key);
// it will print 'hello' and then 'because'
Well its not an array anymore, its a string. arr[0] will return the first letter.
If you want to get the objects from it you need to parse it ( try JSON.parse )
JSON.stringify() does exactly what it sounds like. It turns the javascript object into a string. So when you do arr[0] you are getting the first letter in the string. You need to turn it back into a javascript object if you want to get the actual values.