Last active
October 14, 2024 08:10
-
-
Save Fanoflix/e62011f378cdd84cd790b322fc114688 to your computer and use it in GitHub Desktop.
Ctrl + Enter to submit Form (Typescript)
This file contains 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
document.body.addEventListener("keydown", (e: KeyboardEvent) => { | |
if (!(e.key === "Enter" && (e.metaKey || e.ctrlKey))) return | |
if ('form' in e.target) { | |
const formElement = e.target.form as HTMLFormElement; | |
formElement?.submit(); // or formElement?.requestSubmit() depending on your usecase | |
} | |
}) | |
Unfortunately, the e.target as HTMLFormElement
isn't the most precise coercion, because the .form
receives the any
type:
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();
}
}
@oleksandr-danylchenko Thanks! Updated the gist.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.