Submit The Form Using Enter
WEBINAR: On-demand webcast
How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >
OK, form fans, this is one that you've been requesting for a long time now. It's not that I've been ignoring your requests, it's just that . . . well . . . OK, I've been ignoring your requests. Sorry. I'm on it now.
Here's the concept: You have a form. You ask your user to fill it in and then submit it. Many of you want the form to submit all by itself when the user hits "Enter". I never saw any great benefit to this as part of a guestbook form. There are too many items to fill in, and what if the user fills in the last item out of order? Then you'd get a half-finished form submitted.
I'm presenting this is as a single form element submit, like a database search or a simple email or name submit. You can see those all over the place now because everyone wants to put out a newsletter, including me.
<FORM NAME="theform" METHOD="post"
<b>Submit your Name:</b>
<INPUT TYPE="text" name="mardi" size="30"
The Form Code
We'll start with the FORM code.
The form code is no different than any other form you've created before. The form tag offers a NAME, then a METHOD, then the ACTION. I have this one set to work as a simple mailto: form, but it can just as easily work by attaching the output to a CGI. Just put the path to the CGI right there after the ACTION, like you normally would. The name of the form is "theform". How's that for originality, huh?
The INPUT TYPE is a text box. Its NAME is "mardi". It's set to a size of 30 and a maxlength of 30.
Here it is one more time, since we're a little too far down the page for you to see it above:
The script is super simple. It's a function triggered by the onUnfocus Event Handler in the form element. Remember that? The command onUnfocus works when focus is taken off of an element. You probably could have guessed that. The movement that takes focus away from the form element? Why, the user hitting Enter. See how it all works?
Once focus has been put on and then taken off of the text box, the line document.theform.submit() fires up. That is the hierarchy line that takes the content of something called "theform" and submits it as if you clicked a submit button.
That's really all there is to it.
You can pretty much plop this on your page anywhere you want it, but I would suggest putting the function up in the head commands if you can.
This is a clever trick, but remember that you might run into trouble if you use it as part of a larger script. Stick with single elements like I showed above and you'll do just fine.