How to create a JSON object (form elements) of a dynamic html form?

Trying to create dynamic HTML forms and save them, I can create dynamic forms using bootstrap, but on sending I struggle to create JSON of this dynamic form. I want 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.

+4
source share
1 answer

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/

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

+3
source

Source: https://habr.com/ru/post/1568297/


All Articles