-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>
3
  • It will work fine, once you properly initialize item as an empty array, before you try to access item[i]. Commented Feb 17, 2022 at 7:29
  • Thank you very much. I just executed the same exact code and it worked!!! I appreciate your kind help. Commented Feb 17, 2022 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. Commented Feb 17, 2022 at 11:42

1 Answer 1

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]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Glad to help @ShahoSabbar! Consider accepting the answer by clicking on that tick :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.