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 | |
} | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Unfortunately, the
e.target as HTMLFormElement
isn't the most precise coercion, because the.form
receives theany
type:A bit more robust handling would look like this: