Javascript 用数组填充表单字段
如何获取数组值并填充现有的文本字段。 例如,数组有5个值,有5个文本字段Javascript 用数组填充表单字段,javascript,Javascript,如何获取数组值并填充现有的文本字段。 例如,数组有5个值,有5个文本字段 Array [ tom, Matt, Lucy, Suzanna, Hank ] <input type="text" name="firstName" value=""> <input type="text" name="firstName" value=""> <input type="text" name="firstName" value=""> <input type="
Array [ tom, Matt, Lucy, Suzanna, Hank ]
<input type="text" name="firstName" value="">
<input type="text" name="firstName" value="">
<input type="text" name="firstName" value="">
<input type="text" name="firstName" value="">
<input type="text" name="firstName" value="">
Array[汤姆、马特、露西、苏珊娜、汉克]
您可以将数组作为一个整体进行迭代,或者只需逐个访问每个数组值您应该能够使用类似于以下的方法来迭代
元素,并弹出每个名称,直到它们都已用尽:
// Your array
var array = ['Tom', 'Matt', 'Lucy', 'Suzanna', 'Hank'];
// Loop through the array and target the next available textbox
for(var input in document.getElementsByName('firstName')){
// If there are any names to use, use one
if(array.length > 0){
// Pop the next name off of your array and set the value
// of your textbox
input.value = array.pop();
}
}
如果实际使用上述示例设置值时遇到任何问题,则始终可以使用稍微不同的循环来处理:
// Your array
var array = ['Tom', 'Matt', 'Lucy', 'Suzanna', 'Hank'];
// Store your input elements
var inputs = document.getElementsByName('firstName');
// Loop through the array and target the next available textbox
for(var i = 0; i < inputs.length; i++){
// If there are any names to use, use one
if(array.length > 0){
// Pop the next name off of your array and set the value
// of your textbox
inputs[i].value = array.pop();
}
}
//您的数组
var数组=['Tom','Matt','Lucy','suzana','Hank'];
//存储输入元素
var inputs=document.getElementsByName('firstName');
//循环遍历数组并指向下一个可用的文本框
对于(变量i=0;i0){
//从数组中弹出下一个名称并设置值
//你的文本框
输入[i].value=array.pop();
}
}
您可以使用您提供的数据查看以下内容和输出:
您可以通过多种不同的方式来实现。 e、 g 给字段一个类,并使用jquery向其添加值
<input type="text" class="damn" name="firstName" value="">
<input type="text" class="damn" name="firstName" value="">
<input type="text" class="damn" name="firstName" value="">
<input type="text" class="damn" name="firstName" value="">
<input type="text" class="damn" name="firstName" value="">
更新:您也可以使用Rion Williams在上面创建的方法。编写一个函数,在输入上循环并添加数组中的下一项。
var currIndex = 0;
$(document).ready(function(){
$(".damn").each(function(){
$(this).val(myarray[currIndex++]);
});
});