0

I'm trying to dynamically create buttons on a page for a random selection process based on predefined sets of data, but it pulls back a string (ex. "SouthProvinceA2") instead of from before when I was manually passing in the parameter (area name) in the HTML button onclick=generate(SouthProvinceA2)

Is it possible to convert the string to a variable name for this purpose? Thanks!

const areas = [
  "Starter",
  "PocoPath",
  "SouthProvinceA2"
]

const SouthProvinceA2 = {
  monsters: ["Monster1", "Monster2", "Monster3"]
}

areas.forEach(area => { //...
      const newDiv = document.createElement("div");
      const newButton = document.createElement("button");
      newButton.onclick = function() {
          var result = document.getElementById("result");
          numResult = numResultGen(0, area.monsters.length) //this is where it errors
          namedResult = area.monsters[numResult]
          result.innerHTML = area.monsters[numResult]
          setter(namedResult)

I tried looking up other solutions and using eval() and assigning it to window, but I couldn't out how to get both of them to work and they had other errors that seemed further down the wrong path.

chloe
  • 1
  • 1
  • 1
    Don't use separate variables. Create an object with key `SouthProvinceA2`, then access the object property `provinces[area]` – Barmar May 09 '23 at 17:39
  • 1
    @chloe - I think you didn't quite understand Barmar's comment, since the edited question still has `const SouthProvinceA2 = ___` in it. See the linked question's answers for details. Basically you'd have `const areas = { SouthProvinceA2: { monsters: ___}, AnotherArea: { monsters: ___} /*...*/ };` and then `areas[areaName].monsters` accesses the monsters for the area matching the string in `areaName`. – T.J. Crowder May 09 '23 at 17:44

0 Answers0