0

i have following row in 2 nested for loops:

document.getElementById("sm" + i + "b" + j).innerHTML = jsonval.values.sm1b1;
                                                                       ^^^^^^

i would need to change the variable in the loop like the id of the element. so "sm" + i + "b" + j but to do so I need to have it as a string.. how can I access the variable dynamically by generating the variable name?

sharkyenergy
  • 3,842
  • 10
  • 46
  • 97

3 Answers3

3

Try formulating a key (id) first, then access the element by that ID. Finally, set the value by using square-bracket notation.

const id = `sm${i}b${j}`;
document.getElementById(id).innerHTML = jsonval.values[id];
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

if jsonval.values is an object type variable then u can construct ur string using the syntax

object[`sm${i}b${j}`]
Daniel Paul
  • 495
  • 1
  • 6
  • 13
0

Did you think to access the value of values object with :

values["sm"+i+"b"+j]

instead of :

values.sm1b1
  • Hi @thibault-spriet, welcome to stackoverflow. Please be more elaborate in your answers. You can have a look at https://stackoverflow.com/help/how-to-answer on how to write a great answer. Welcome – kplus Jun 18 '21 at 06:47