我有一个数组的文本值如下所示
var valArray = ["first", "second", "third", ……… ];
和多个表单输入
<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
………
如何将数组中的第一个值添加到第一个输入中,将第二个值添加到第二个输入中,将数组中的第三个值添加到第三个输入中?
数组中的值数等于输入数。但两者的数量是可变的。
谢谢.
循环输入并按索引插入值
null
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="">
您可以创建与数组中的值一样多的输入元素,如:
const values = ["first", "second", "third"];
const div = document.querySelector('#result');
values.forEach(value => {
const input = document.createElement('input'); // create input el here
input.value = value; // set value of input which is in array
div.appendChild(input); // append to div (jsut for ref)
})
<div id='result'> </div>
您可以使用Javascript作为Folors来完成此操作:
null
const inputs = document.querySelectorAll('.input');
var values = ["value1", "value2", "value3"]
for (let i = 0; i < inputs.length; i++) {
inputs[i].value = values[i];
}
<div>
<input class="input" value="" placeholder="input1"/>
<input class="input" value="" placeholder="input2"/>
<input class="input" value="" placeholder="input3"/>
</div>