Insert variables from array into multiple inputs

I have an array with text values like this

var valArray = ["first", "second", "third", ……… ];

And multiple form inputs like this

<input type=‘text’ name=‘field[]’ value=‘’> //set ‘first’ here
<input type=‘text’ name=‘field[]’ value=‘’> //set ‘second’ here
<input type=‘text’ name=‘field[]’ value=‘’> //set ‘third’ here
………

How to add first value from array into first input, second into second, and third value from array into third input?

Number of values in array is equal to number of inputs. But number of both is variable.

Thank you.

Answer

Loop through the inputs and insert the value by index

var valArray = ["first", "second", "third"];

document.querySelectorAll('input').forEach((input, index) => {
  input.value = valArray[index];
});

// jquery
// $('input').each((index, input) => $(input).val(valArray[index]));
<input type=‘text’ name=‘field[]’ value="">
<input type=‘text’ name=‘field[]’ value="">
<input type=‘text’ name=‘field[]’ value="">

Leave a Reply

Your email address will not be published. Required fields are marked *