A common task for web developers is capturing the case where the user presses the enter/return key on his keyboard when filling out a form, instead of clicking the “submit” button.
I’ve seen many, many developers reach for the key press events and check whether enter was pressed (oh, char code 13, how I hate you). That of course works, but is nasty. Here’s is an example using Angular.js (which I’m sure you can translate easily to your favorite way of doing this, such as jQuery’s
1 2 3 4
1 2 3 4 5 6 7
And of course, as you can see,
signUpIfEnterPressed() is a function that has to check the event’s keyCode and compare it to the value of enter (13) and then, and only then, call the
signUp() function. Bleh. Not good enough!
Turns out the people who wrote browsers already did most of the work related for us, we just have to reach out and use their work.
The trick is basically that the
<form> element already is listening for these enter presses on all the inputs inside it. Pressing enter in an input in a form triggers the form’s submit event to be fired.
That means that we can now cleanly remove
signUpIfEnterPressed() and replace the code with:
1 2 3 4
And of course the solution is pretty much the same regardless of what JS libraries you’re using (e.g. in jQuery you can do
$('.sign-up-section').submit(signUp)), since this is purely done by the browsers.