JavaScript Tip: Submit Form On Enter Key
A common practice with search forms is to have them submit when the enter key is pressed, instead of requiring the user to use their mouse to press the submit button (or using tab key to tab to the submit button).
Here is a simple way to do that in JavaScript:
First, define a input box:
<input name="txtsearchentries" id="txtsearchentries" type="text" size="13" value="" />
Second, create a function to be placed in the head area of the webpage:
//see if the user pressed the enter key while using a specific control
function submitSearchOnEnter(variable)
{
var keyCode;
//get whatever key was just pressed
//try to account for different methods of getting
//event keys depending on implementation
if(window.event)
{
keyCode = window.event.keyCode;
}
else if(variable)
{
keyCode = variable.which;
}
//if the key was the enter key, perform the necessary function
if(keyCode == 13) //13 = enter key
{
//here is where you process the form item or call a function to do that
searchEntries(); //call search
}
}
Third, you need to assign the function above to to be an event handler:
//assign an event handler to the search box so we can have it
//submit when user presses enter
document.getElementById('txtsearchentries').onkeyup = submitSearchOnEnter;
That’s it. Should be able to assign it similarly to other fields on the page too, but then you would need to think of how to create separate functions to handle each.
Tags: enter, forms, javascript, key, press, submit, Uncategorized
August 26th, 2008 at 3:41 pm
your script did not work
August 26th, 2008 at 4:00 pm
Really? If you want to write some details such as what browser you are using, it would be helpful in figuring out the problem.
January 8th, 2009 at 10:50 pm
hey the character code==13 thing is a no-go on firefox