如何创建动态html表单的创建JSON对象(表单元素)?

尝试创建动态HTML表单并保存它们,我可以使用bootstrap创建动态表单但是在提交时我正在努力创建这个动态表单的JSON。 我希望保存这样的东西

{ "form" : [ { "name" : "username", "id" : "txt-username", "caption" : "Username", "type" : "text", "placeholder" : "Eg user@example.com" }, { "name" : "password", "caption" : "Password", "type" : "password" }, { "type" : "submit", "value" : "Login" } ] } 

我不知道我怎么能做到这一点。

这应该这样做:

 function getAttrs(DOMelement) { var obj = {}; $.each(DOMelement.attributes, function () { if (this.specified) { obj[this.name] = this.value; } }); return obj; } $("form").each(function () { var json = { "form": [] }; $(this).find("input").each(function () { json.form.push(getAttrs(this)); }); $(this).find("select").each(function () { var select = getAttrs(this); select["type"] = "select"; var options = []; $(this).children().each(function () { options.push(getAttrs(this)); }); select["options"] = options; json.form.push(select); }); console.log(json); }); 

演示: http : //jsfiddle.net/j1g5jog0/

更新: http : //jsfiddle.net/j1g5jog0/5/