Save HTML schema form to JSON
Is there a way to save HTML Form schema to JSON?
eg. when i have something like this
<form>
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
</form>
How can I achieve something like this:
[
{
field: 'input',
type: 'text',
name: 'firstname'
},
{
field: 'input',
type: 'text',
name: 'lastname'
},
]
I don't mean that this should be the exact output as above, but how can I achieve something like this?
source to share
The idea is to do something like this. You can iterate over the shape of a elements
collection of elements and use each element to retrieve the information you need.
In the code below, I used a method Array.prototype.map
, but it might be more convenient to use a simple loop for
. This will give you more customization options.
function serializeSchema(form) {
return [].map.call(form.elements, function(el) {
return {
type: el.type,
name: el.name,
value: el.value
};
});
};
var form = document.querySelector('form'),
schema = serializeSchema(form);
alert(JSON.stringify(schema, null, 4));
<form>
<input type="text" name="firstname" value="Test">
<input type="text" name="lastname">
<select name="age" id="">
<option value="123" selected>123</option>
</select>
<input type="checkbox" name ="agree" value="1" checked> agree
</form>
Also one more note. What you are trying to achieve is very similar to what the jQuery method does $.fn.serializeArray
(it doesn't collect type
). However, it is quite easy to extend serializeArray
so that it returns type
items as well .
source to share