Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. I am looking to save something like this

{
 "form" :
    [

        {
            "name" : "username",
            "id" : "txt-username",
            "caption" : "Username",
            "type" : "text",
            "placeholder" : "E.g. [email protected]"
        },
        {
            "name" : "password",
            "caption" : "Password",
            "type" : "password"
        },
        {
            "type" : "submit",
            "value" : "Login"
        }
    ]
}

I am not sure how i can achieve this.

like image 670
user986508 Avatar asked Dec 05 '25 09:12

user986508


1 Answers

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/

like image 85
Johan Karlsson Avatar answered Dec 07 '25 21:12

Johan Karlsson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!