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). Update: I attempted to find a solution for working in Firefox, but the code I added has not been tested personally.

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; this doesn't seem to work in Firefox, so try the code below...
      keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
  }
  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.

This entry was posted in General and tagged , , , , , , . Bookmark the permalink.