Skip to content

Instantly share code, notes, and snippets.

@ramonrails
Created March 8, 2020 07:58
Show Gist options
  • Save ramonrails/e52bc7f8cefcf01ed224d5921f122bc1 to your computer and use it in GitHub Desktop.
Save ramonrails/e52bc7f8cefcf01ed224d5921f122bc1 to your computer and use it in GitHub Desktop.
HTML form elements to JSON
// developer: RamOnRails.in
// purpose: fetch form data as JSON
// parameters:
// form: the form object
// arg: [optional] query selector to pick elements
// defaults: arg: "input, select, textarea"
function toJSON(form, arg = null) {
// we will capture the elements and their values in this object
let hash = {};
// arg converted to string
// default elements string concatenated with arg string (duplicates do not matter)
// all specified elements selected from the `form`
// ES6 spread operator used to make an array of the selected elements (we need array, not collection of objects)
// elements array collection all selected
const elements = [...form.querySelectorAll('input, select, textarea, ' + String(arg))];
// `map` will loop through each element and run the function on each
// we are adding every element into the `hash` we declared & defined above
elements.map((element) => { hash[element.name] = element.value; });
// converting object to JSON string
// return the JSON string
return JSON.stringify(hash);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment