简体   繁体   English

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

[英]How to create create JSON object ( of form elements) of dynamic html form?

Trying to create dynamic HTML forms and save them, I can create dynamic forms using bootstrap but on submit i am struggling to create JSON of this dynamic form. 尝试创建动态HTML表单并保存它们,我可以使用bootstrap创建动态表单但是在提交时我正在努力创建这个动态表单的JSON。 I am looking to save something like this 我希望保存这样的东西

{
 "form" :
    [

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

I am not sure how i can achieve this. 我不知道我怎么能做到这一点。

This should do it: 这应该这样做:

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);
});

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM