Last active
February 4, 2019 17:44
-
-
Save goatandsheep/4082bb6251249086c3ccff57c6e34d88 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* es6 | |
*/ | |
function filterForms(target) { | |
const formData = (new FormData(target)).entries() | |
let filtered = {} | |
for (let pair of formData) { | |
// filtered[pair[0]] = pair[1].trim() | |
if (typeof filtered[pair[0]] === 'undefined') { | |
filtered[pair[0]] = pair[1].trim() | |
} else if (Array.isArray(filtered[pair[0]])) { | |
filtered[pair[0]].push(pair[1].trim()) | |
} else { | |
let temp = [] | |
temp.push(filtered[pair[0]]) | |
temp.push(pair[1].trim()) | |
filtered[pair[0]] = temp | |
} | |
} | |
return filtered | |
} | |
/** | |
* es5 | |
*/ | |
function filterForms(target) { | |
const inputs = target.querySelectorAll('input') | |
let filtered = {} | |
inputs.forEach(entry => { | |
const name = entry.name | |
if (entry.multiple) { | |
const options = entry.selectedOptions | |
const files = entry.files | |
const values = [] | |
if (options) { | |
for(let pair of options) { | |
values.push(pair.value) | |
} | |
} else if (files) { | |
for(let file of files) { | |
values.push(file) | |
} | |
} | |
if (values.length) { | |
filtered[name] = values | |
} | |
} else { | |
const val = entry.value | |
if (typeof val === "string") { | |
filtered[name] = val | |
} | |
} | |
}) | |
return filtered | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment