Posts Tagged: javascript call enter key


25
Jan 08

Call Javascript function on pressing ‘Enter’ key

In most of the search pages you might have noticed how you can type your queries into the search box and search by pressing the enter key instead of having to click the ‘Search’ button present in the page.

Wondering how to do it? Well, wait no more. Implement the same feature in your pages too.

All we need to know is the key code for the enter key which happens to be ’13′.

Then under the event onKeyDown we can call the javascript which submits the page.

Go through the example below and you’ll know it all.

{

<input type=”text” onKeydown=”Javascript: if (event.keyCode==13) Search();”>

<input type=”button” value=”Search” onClick=”Search();”>

}

The above code will display a text box followed by a button labelled Search as shown in the figure below:(Note: Click on the thumbnail to view)

Search On enter key press

You’ll notice that the onClick event of the Search button calls a javascript function named Search(). To have the same function called on pressing the enter key when the cursor is in the text box, we check if the keycode is 13 and subsequently call the Search() function.