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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With