Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save HTML form schema to JSON

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?

like image 927
Dariusz Mydlarz Avatar asked Aug 03 '26 01:08

Dariusz Mydlarz


1 Answers

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.

like image 51
dfsq Avatar answered Aug 05 '26 13:08

dfsq



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!