Submitting a form when the user hits enter…

February 16, 2010Jake DiMare

Some web coding fixes turn out to be so simple that there is not a lot of good direction on the topic easily found online. Ironically, what little information I could find all turned out to be overcomplicated and didn’t work. For a self-taught hack like me this means figuring it out for myself. To save you the trouble, in case you are anything like me, I will try to share what I learned. If you have questions please don’t hesitate to ask in the comments.
Recently a user requested a revision to a form with two fields that makes it possible to submit the form when the user enters a value into the second field and clicks ‘Enter’. As you may have noticed using Google, if a form has one field and the user hits enter while the focus is on the field, it will submit. However, if a form has more than one field, by default, it is necessary to use the submit button. Thankfully, we can use a form field attribute and a very simple function to get around this.
First, revise the form field with an attribute that will recognize the event called ‘onKeyUp=’.  There is also an attribute called ‘onKeyPress=’ but this can get sticky because Safari assigns the return key (above shift) and the enter key (on the numeric keypad)  different values onKeyPress.
Next, let’s assume the desired result of submitting the form is to call another function used to validate the form called ‘runForm()’. By simply adding onKeyUp=”runForm()” the form will submit. However, this is not finished. By simply stopping here the validation function will run regardless of which key the user hits. For obvious reasons, this will not do.
Instead, wrap the ‘runForm()’ function with another function, we’ll call ‘enterForm()’, containing an if statement that tests the event to determine which key the user hit. We’ll also need to pass the event to the function so it can test which key was hit. Thus, the entire form field will now look like this:

<input id=”Your_ID” name=”Your_Name value=”Your_Value” onKeyUp=”enterForm(event)”>

Finally, up in the header we need to create this ridiculously simple new function:

function enterForm(event) {
if(event.keyCode == 13) {
//alert(“You pressed enter”);
runForm();
}
}

function enterForm(event) {

if(event.keyCode == 13) {

runForm();

}

}

You may have deduced, the value of the return and the enter key onKeyUp is ’13’. What we have done is created a function called enterForm() and passed in the event variable. The function checks the keyCode value associated with the event using an if statement. If the keyCode value is 13 the function calls the separate validation function. If the keyCode value is anything but 13 the function does nothing.

Like I said earlier, if you have any questions about this please don’t hesitate to ask …I’ll do my best to answer.


Prev Post Next Post