[英]How to create an array from inputs?
I created multiplied input fields: 我创建了多个输入字段:
<div class="form-text-field first-name field-group">
<input data-index="1" type="text" id="firstName1" class="signup-input firstName" name="first[1]" placeholder="">
</div>
<div class="form-text-field email field-group">
<input type="text" data-index="1" id="inputMail1" class="signup-input text-value ignore" name="email[1]" placeholder="${message(code:"signup.redesign.placeholder.eg.email")}"/>
<span class="common-sprite disNone sign-up-cross first clone"></span>
</div>
I have a code in the JS file which clone every input. 我在JS文件中有一个代码可以克隆每个输入。
I have to create arrays from the values of the inputs (one for the email, and one for the first name). 我必须根据输入的值创建一个数组(一个用于电子邮件,一个用于名字)。
Here is the function: 这是函数:
var arrEmail = []
var arrName = []
function add() {
var obj = {};
var partner = {}
$('.email input[type="text"]').each(function() {
obj[this.data-index] = this.value;
});
arrEmail.push(obj)
$('.first-name input[type="text"]').each(function() {
partner[this.data-index] = this.value;
});
arrName.push(partner)
console.log(arrEmail[0])
}
I didn't succeed to get the arrays in this code. 我没有成功获得此代码中的数组。 How do I fix it?
我如何解决它?
You have some mistakes. 你有一些错误。
$('.email input[type="text"]').each(function({
. You forgot to close bracket. $('.email input[type="text"]').each(function({
。您忘记了右括号。 I fix your code. 我修复了您的代码。
var arrEmail = [];
var arrName = [];
function add() {
var obj = {};
var partner = {};
$('.email input[type="text"]').each(function(item) {
obj[$(this).data('index')] = $(this).val();
});
arrEmail.push(obj);
$('.first-name input[type="text"]').each(function() {
obj[$(this).data('index')] = $(this).val();
});
arrName.push(obj);
console.log(arrEmail);
console.log(arrName);
}
$('#test').on('click', add);
Upd #1 更新#1
Haven't shown all conditions. 尚未显示所有条件。 Fixed it.
修复。
使用$(this).data('index')
代替this.data-index
You can handle this with a single array: 您可以使用单个数组来处理:
var myUsers= [];//this might be object that you store the user information
$('.first-name input[type="text"]').each(function(item) {
//first create the user information
var myUser = new Object();
myUser.Username = $(this).val();
myUser.Email= $(this).next().val();
//then add the user information to the myUsers array
myUsers.push(myUser );
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.