Reputation: 3002
Is there any way to save HTML Form schema to JSON?
E.g. 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 i can achieve somehting like this:
[
{
field: 'input',
type: 'text',
name: 'firstname'
},
{
field: 'input',
type: 'text',
name: 'lastname'
},
]
I dont mean that it has to be exact output as above, but how I can achieve something similar?
Upvotes: 3
Views: 1226
Reputation: 193271
The idea is to do something like this. You can iterate through form elements
collection of elements, and use every element to extract necessary information.
In code below I used Array.prototype.map
method, but maybe it would be more convenient to go with simple for
loop. It would give you more room for customization.
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 jQuery's $.fn.serializeArray
method does (it doesn't collect type
). However it's pretty simple to extend serializeArray
to make it also return type
of the elements.
Upvotes: 5