Skip to content

Instantly share code, notes, and snippets.

@c3ry5
Last active November 4, 2018 11:07
Show Gist options
  • Save c3ry5/f5d17eaba1b6f1807bbc to your computer and use it in GitHub Desktop.
Save c3ry5/f5d17eaba1b6f1807bbc to your computer and use it in GitHub Desktop.
A script to serialize a form using native js - https://codepen.io/anon/pen/VVwopj
window.serialize = {
simple(form) {
const formel = document.querySelectorAll(form);
const inputs = formel[0].querySelectorAll("input, select, textarea");
const obj = {};
let key;
for (key in inputs) {
if (inputs[key].tagName) {
if (inputs[key].type === "checkbox") {
obj[inputs[key].name] = inputs[key].checked === true ? inputs[key].value : false;
} else {
obj[inputs[key].name] = inputs[key].value;
}
}
}
return obj;
},
nested(form) {
const data = this.simple(form);
const obj = {};
let key;
let fieldParts;
let i;
for (key in data) {
if (data.hasOwnProperty(key)) {
fieldParts = key.split(".");
if (fieldParts.length === 1) {
obj[fieldParts[0]] = data[key];
} else {
for (i = 0; i < fieldParts.length; i = i + 1) {
currentKey = fieldParts[i];
if (i < fieldParts.length - 1) {
nextKey = fieldParts[i + 1];
if (isNaN(nextKey)) {
thisValueType = {};
} else {
thisValueType = [];
}
}
if (i === 0) {
if (!(currentKey in obj)) {
obj[currentKey] = thisValueType;
}
parent = obj[currentKey];
} else {
if (i === fieldParts.length - 1) {
parent[currentKey] = data[key];
} else {
if (!(currentKey in parent)) {
parent[currentKey] = thisValueType;
}
parent = parent[currentKey];
}
}
}
}
}
}
return obj;
}
};
<form class="form">
<dl> <dt>Give us your five friends' names and emails</dt>
<input type="hidden" name="test" value="test single" />
<dd>
<label>Email
<input type="text" name="person.friends.0.email" value="[email protected]" />
</label>
<label>Name
<input type="text" name="person.friends.0.name" value="name 1" />
</label>
</dd>
<dd>
<label>Email
<input type="text" name="person.friends.1.email" value="[email protected]" />
</label>
<label>Name
<input type="text" name="person.friends.1.name" value="name 2" />
</label>
</dd>
</dl>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment