Skip to content

Instantly share code, notes, and snippets.

@ardislu
Last active September 1, 2024 23:43
Show Gist options
  • Save ardislu/67848ceac4f836b254fa7ed01f485725 to your computer and use it in GitHub Desktop.
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`.
<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