Last active
September 1, 2024 23:43
-
-
Save ardislu/67848ceac4f836b254fa7ed01f485725 to your computer and use it in GitHub Desktop.
A minimal example of the most concise way to get the values from a vanilla HTML `<form>` element and assign the values to JavaScript variables in 2024. Notice that the object keys are based on the `<input>`'s `name` attribute and not `id`.
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
<form> | |
<input name="ex1"> | |
<input name="ex2"> | |
<input name="example-with-hypens"> | |
<button>Submit</button> | |
</form> | |
<script> | |
document.querySelector('form').addEventListener('submit', e => { | |
e.preventDefault(); | |
const { ex1, ex2, 'example-with-hypens': exampleWithHyphens } = Object.fromEntries(new FormData(e.target)); | |
console.table({ ex1, ex2, exampleWithHyphens }); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment