Last active
February 7, 2019 12:57
-
-
Save DusterTheFirst/cecb6c5ec540cbf51f776b2653af79b7 to your computer and use it in GitHub Desktop.
HTML form to JSON form for auto submission
This file contains hidden or 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
/** 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