将Jquery对象数组放入html表单元素

时间:2018-06-02 07:32:53

标签: javascript jquery

我有这个jquery对象数组

(2) [{…}, {…}]
0:{Name: "name", NRIC/Passport: "nric", Date of Birth: "2018-06-02", Occupation: "occ", Weight: "123", …}
1:{Name: "name2", NRIC/Passport: "nric2", Date of Birth: "2018-06-02", Occupation: "occ2", Weight: "234", …}
length:2
__proto__:Array(0)

我想将它们放入html表单元素中。目前我就是这样做的:

$.each(spouses,function(key,value){
       $.each(value,function(int_key,int_value){
       $("#spouse_data").append("<div class='col-sm-4'><label>"+int_key+"</label><input type='text' readonly class='form-control' name='spouse' value="+int_value+"></div>");
    });
});

但是,我无法为每个表单元素设置名称,以便在提交表单时可以接收数据。 还有另一种选择,而不是使用这种格式的对象

"Name of obj":data

我用

name_of_obj:data

第二个问题是我无法插入标签名称。我想知道这样做的最佳方法是什么。希望有人可以提供帮助。

3 个答案:

答案 0 :(得分:0)

如何将以下内容用于表单元素:

name="spouse[' + index + ']"

使用数组字段类型而不是字符串是否有意义?

答案 1 :(得分:0)

将对象更改为一组看起来像这样的对象:

[{ value: 'name', label: 'Name', name: 'name' }, { value: 'nric', label: 'NRIC/Passport', name: 'nric_password' }]

然后使用Array.prototype.forEach迭代它:

&#13;
&#13;
[{
  value: 'name',
  label: 'Name',
  name: 'name_for_form_submission'
}, {
  value: 'nric',
  label: 'NRIC/Passport',
  name: 'nric_password'
}].forEach((item) => {
  console.log(`${item.label}: ${item.value}, form name: ${item.name}`)
})
&#13;
&#13;
&#13;

答案 2 :(得分:0)

检查此代码,你可以这样做

https://codepen.io/creativedev/pen/pKjamd

var obj = {
        0: {Name: "name", "NRIC/Passport": "nric", "Date of Birth": "2018-06-02", Occupation: "occ", Weight: "123"},
        1: {Name: "name2", "NRIC/Passport": "nric2", "Date of Birth": "2018-06-02", Occupation: "occ2", Weight: "234"}
        };
$.each(obj,function(key,value){
    $.each(value,function(key1,value1){
    $("#data").append("<div class='col-sm-4'><label>"+key1+"</label><input type='text' readonly class='form-control' name='spouse' value="+value1+"></div>");
    });
     $("#data").append("<br/><br/>");
});