Last active
April 11, 2022 12:29
-
-
Save AlphaT7/3d074c8c277cf709372234c04aa78f6a to your computer and use it in GitHub Desktop.
JavaScript Serialize Form Objects and convert to JSON Object
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
<!-- -- !IMPORTANT! -- MUST USE NAME INSTEAD OF ID FOR FORM ELEMENTS --> | |
<form id="form_id"> | |
<select name="select1"> | |
<option value="opt1" selected>Option 1</option> | |
<option value="opt2">Option 2</option> | |
<option value="opt3">Option 3</option> | |
</select> | |
<select name="select2"> | |
<option value="opt1" selected>Option 1</option> | |
<option value="opt2">Option 2</option> | |
<option value="opt3">Option 3</option> | |
</select> | |
<input type="text" name="textinput1" value="search"/> | |
<input type="submit"> | |
</form> |
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
/*-- -- !IMPORTANT! -- Unfortunately this method does not get checkbox or radio button checked true/false --*/ | |
let data = JSON.stringify( | |
Object.fromEntries( | |
new FormData(document.querySelector("#form_id")).entries() | |
) | |
) | |
// data returns: {select1: "opt1", select2: "opt1", textinput1: "search"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Allows getting all form element values from a single form id.