Created
April 29, 2020 08:09
-
-
Save wapcrazut/2c3e09118f9326410cb1099468244c2f to your computer and use it in GitHub Desktop.
TypeScript Form Serializer
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
/* | |
* Serialize all form data into a query string (TypeScript version) | |
* Based on the Chris Fernandi function. | |
* 2020 Williams Crazut, MIT License, https://webdeveloperguy.com | |
*/ | |
function serialize(form: HTMLFormElement) | |
{ | |
let serialized = []; | |
for (let i = 0; i < form.elements.length; i++) { | |
let field = form.elements[i] as HTMLInputElement | HTMLSelectElement; | |
if (!field.name | |
|| field.disabled | |
|| field.type === 'file' | |
|| field.type === 'reset' | |
|| field.type === 'submit' | |
|| field.type === 'button' | |
) continue; | |
if (field instanceof HTMLSelectElement) { | |
if (field.type === 'select-multiple') { | |
for (let n = 0; n < field.options.length; n++) { | |
if (!field.options[n].selected) continue; | |
serialized.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(field.options[n].value)); | |
} | |
} else { | |
serialized.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value)); | |
} | |
} | |
if (field instanceof HTMLInputElement) { | |
if (field.checked) { | |
serialized.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value)); | |
} | |
} | |
} | |
return serialized.join('&'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment