Posts Tagged ‘Uncategorized’

JavaScript Tip: Submit Form On Enter Key

Sunday, May 4th, 2008

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.

Break it up!

Saturday, December 9th, 2006

I want to write more about programming and development, but I don’t want to put it in my main blog, so I made another blog. Alright, Mission Staaaaarrrrt!





 

 
Stock Photo Website
Tech Learning Site

Popular Article Tags

Recent Article Comments

Archives