0
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.

2 Answers2

1

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.
Nicolas
  • 8,077
  • 4
  • 21
  • 51
0

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.

Eggon
  • 2,032
  • 2
  • 19
  • 38