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.
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.
Share Improve this question asked Dec 19, 2014 at 10:17 user986508user986508 1992 gold badges5 silver badges14 bronze badges 4- what exacltly you want to achieve? you want to send all your form propertis? or only inputs? – nowiko Commented Dec 19, 2014 at 10:19
- All form properties which i created dynamically (html form). I want to save that JSON object of that form properties (type, value(if any), name, id..). – user986508 Commented Dec 19, 2014 at 10:21
- for send only values you can use $("form").serializeArray();...but for attributes I dont know...I think attr() function may help you. – nowiko Commented Dec 19, 2014 at 10:25
- I was trying with DOM, but there should be some standard way.. Ahhh – user986508 Commented Dec 19, 2014 at 10:28
1 Answer
Reset to default 5This 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/j1g5jog0/
Update: http://jsfiddle/j1g5jog0/5/