Skip to content

Instantly share code, notes, and snippets.

@Fanoflix
Last active May 13, 2024 07:51
Show Gist options
  • Save Fanoflix/e62011f378cdd84cd790b322fc114688 to your computer and use it in GitHub Desktop.
Save Fanoflix/e62011f378cdd84cd790b322fc114688 to your computer and use it in GitHub Desktop.
Ctrl + Enter to submit Form (Typescript)
document.body.addEventListener("keydown", (e: KeyboardEvent) => {
if (!(e.key === "Enter" && (e.metaKey || e.ctrlKey))) return
const form = (e.target as HTMLFormElement).form
if (form) form.submit() // or form.requestSubmit() depending on your usecase
})
@Fanoflix
Copy link
Author

Fanoflix commented May 28, 2023

Line # 4 is basically a check for the existence of the form element as the target of the event. The e.target.form will yield a form if any one of the inputs within the form is focused.

So pressing Ctrl+Enter with any input or button element being focused within the form will submit the form.

@oleksandr-danylchenko
Copy link

oleksandr-danylchenko commented May 2, 2024

Unfortunately, the e.target as HTMLFormElement isn't the most precise coercion, because the .form receives the any type:
image


A bit more robust handling would look like this:

(event) => {
	if (!event.target) return;

	const { key, metaKey, ctrlKey } = event;
	if (key !== 'Enter' || !(metaKey || ctrlKey)) return;

	if ('form' in event.target) {
		const formElement = event.target.form as HTMLFormElement;
		formElement?.requestSubmit();
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment