-2

I would greatly appreciate an answer to my question. It's been bugging me for days. I have a list of inputs in my form.

<!DOCTYPE html>
<html>

<div class="form">
<form id="myForm" onsubmit="myFunction()">

<input type="text" id="item1">
<input type="text" id="item2">
<input type="text" id="item3">

</form> 
</div>
<br><br><br><be>

But I want to do this programmatically for a varying number of items, so I tried something like this:

<script>
for (i=1; i<=3; i++) {
    item[i] = document.createElement("input");
    item[i].setAttribute("type", "text");
    myForm.appendChild(item[i]);
}

But it doesn't seem to work. It would work if I didn't use indexed names, but fixed item names, like:

item1 = document.createElement("input");
item1.setAttribute("type", "text");
myForm.appendChild(item1);

But that's not what I need. Can you help me?

</script>
</html>
General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • It will work fine, once you properly initialize `item` as an empty array, before you try to access `item[i]`. – CBroe Feb 17 '22 at 07:29
  • Thank you very much. I just executed the same exact code and it worked!!! I appreciate your kind help. – Shaho Sabbar Feb 17 '22 at 11:33
  • No!!! what am I doing? The exact same code didn't work. I added (var item = [];) before the loop and then it worked!! I really appreciate it CBore. You helped a lot. – Shaho Sabbar Feb 17 '22 at 11:42

1 Answers1

0

You can assign the IDs dynamically as well:

for (i=1; i<=3; i++) {
    item[i] = document.createElement("input");
    item[i].setAttribute("type", "text");
    item[i].setAttribute("id", "item" + i);
    myForm.appendChild(item[i]);
}
Wais Kamal
  • 5,858
  • 2
  • 17
  • 36