这是我的JSFiddle
单击“+”按钮可以克隆并动态附加边界表单元素。
“保存规则”按钮可生成表单字段标签和值的JSON对象。 这是单击“保存规则”按钮时创建的JSON对象。
{
"nameRules": "",
"typeRules": "Type1",
"descriptionRules": "XYZ\n ",
"elhs": "",
"op": "<=",
"erhs": "",
"datatype": "",
"joinop0": "",
"elhs0": "",
"op0": "",
"erhs0": "",
"datatype0": ""
}
如何使用以下格式创建JSON对象?
{
"nameRules": "",
"typeRules": "Type1",
"descriptionRules": "XYZ\n ",
"expressions": [{
"elhs": "",
"op": "<=",
"erhs": "",
"datatype": ""
},
{
"joinop0": "",
"elhs0": "",
"op0": "",
"erhs0": "",
"datatype0": ""
}]
}
非常感谢任何帮助。 谢谢
答案 0 :(得分:1)
嗯,代码可能不太漂亮,因为我不是jquery的专家,但它应该按预期工作:FIDDLE
$('button.btn:contains("Save Rules")').on('click', function(e) {
console.log('hhh', $('form.form-horizontal#rules').find(':input:not(button):not(#joinop)').get());
var jsonData = $('form.form-horizontal#rules')
.find(':input:not(button):not(#joinop)').get()
.reduce(function(acc, ele) {
acc.expressions = acc.expressions||[];
if (ele.closest( "#container" ) || ele.closest('.parent-border')) {
if (ele.closest('.parent-border')) var i = 0;
else var i = $( "#container .child-border" ).index( ele.closest( ".child-border" )) +1
acc.expressions[i] = acc.expressions[i]||{};
acc.expressions[i][ele.name || ele.id] = ele.value;
}
else acc[ele.name || ele.id] = ele.value;
return acc;
}, {});
console.log(jsonData);
alert(JSON.stringify(jsonData, null, 4));
});