Skip to content

Instantly share code, notes, and snippets.

@DusterTheFirst
Last active February 7, 2019 12:57
Show Gist options
  • Save DusterTheFirst/cecb6c5ec540cbf51f776b2653af79b7 to your computer and use it in GitHub Desktop.
Save DusterTheFirst/cecb6c5ec540cbf51f776b2653af79b7 to your computer and use it in GitHub Desktop.
HTML form to JSON form for auto submission
/** An object with string keys and values */
type StringOBJ = { [x: string]: string };
/** Generate a JSON representation of a form */
function generateJSONForm(form: HTMLFormElement): StringOBJ {
// Create empty object
let object = {} as StringOBJ;
// Loop through children
for (let elem of form.children) {
// Get the name of the element
let name = elem.getAttribute("name");
// Make sure the element has a name
if (!name) continue;
// Only send select, input or textarea
if (elem instanceof HTMLSelectElement || elem instanceof HTMLInputElement || elem instanceof HTMLTextAreaElement) {
// Check if the input is a radio button
if (elem instanceof HTMLInputElement && elem.type === "radio") {
if (elem.checked) {
// Assign value
object[name] = elem.value;
}
} else {
// Assign value
object[name] = elem.value;
}
}
}
// Return the completed object
return object;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment