-1

I'm quite new in JavaScript so I'm unsure on some things

for($i = 0; $i < 5; $i ++) {
  <input id="data[$i]" />
}
document.getElementById("data"[count]).value = "Value";
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
Alexander
  • 15
  • 2
  • Does this answer your question? [Javascript getElementById based on a partial string](https://stackoverflow.com/questions/6991494/javascript-getelementbyid-based-on-a-partial-string) – Heretic Monkey Oct 29 '20 at 20:32

1 Answers1

1

You need to put the correct id when using document.getElementById.

Through the html code, the id is set like data[1], data[2], data[3] ... so you need to generate that id name. Instead of "data"[count], you can write as follows to get the id.

`data[${i}]`  // Here, i = 1,2,3,4,5...

Below is the working snippet.

for (let i = 1; i <= 5; i ++) {
  document.getElementById(`data[${i}]`).value = "Value";
}
<input id="data[1]" />
<input id="data[2]" />
<input id="data[3]" />
<input id="data[4]" />
<input id="data[5]" />
Derek Wang
  • 10,098
  • 4
  • 18
  • 39