1

I have a couple of input fields with the following ID:

<input type="text" name="numberC[]" id="numberC[]">
<input type="text" name="numberC[]" id="numberC[]">
<input type="text" name="numberC[]" id="numberC[]">

I fetch data in JSON format via my ajax call and push() certain values in my array.

How could I create a loop that will loop through the array and then inserts each value in one of the above input fields?

so let's say I have the following array:

var testArray = ['hi', 'bye', 'stackoverflow'];

and I have the following 3 input fields:

<input type="text" name="numberC[]" id="numberC[]">
<input type="text" name="numberC[]" id="numberC[]">
<input type="text" name="numberC[]" id="numberC[]">

Whenever I loop through it I unfortunately get the highest value in all of my input fields.

I try to loop through my array in JavaScript and insert each value in each input field. so testArray[0] should go in the first input field, testArray[1] in the second input field and testArray[2] in the third.

Sources I used: Find DOM element by ID when ID contains square brackets?

Danny
  • 39
  • 8

2 Answers2

1

The id in dom is always unique.Instead use document.querySelectorAll to get all the element with same name then loop through them and use the index to check if an element exist in the index of testArray. If so then set the value of the input

var testArray = ['hi', 'bye', 'stackoverflow'];
document.querySelectorAll('[name="numberC[]"]').forEach(function(item, index) {
  if (testArray[index]) {
    item.value = testArray[index]
  }

})
<input type="text" name="numberC[]" id="numberC[1]">
<input type="text" name="numberC[]" id="numberC[2]">
<input type="text" name="numberC[]" id="numberC[3]">
brk
  • 48,835
  • 10
  • 56
  • 78
0

If you change your HTML to have different ids

<input type="text" id="numberC[1]"/>
<input type="text" id="numberC[2]"/>
<input type="text" id="numberC[3]"/>

you can easily set the values like this:

    var testArray = ['hi', 'bye', 'stackoverflow'];
    for(let i in testArray) {
        document.querySelector('#numberC\\[' + (+i+1) + '\\]').value = testArray[i];
    }
Alexey Zelenin
  • 710
  • 4
  • 10