How to capture Enter key press?


In my HTML page, I had a textbox for user to input keyword for searching. When they click the search button, the JavaScript function will generate a URL and run in new window.

The JavaScript function work properly when the user clicks the search button by mouse, but there is no response when the user presses the ENTER key.

function searching(){
    var keywordsStr = document.getElementById('keywords').value;
    var cmd ="http://XXX/advancedsearch_result.asp?language=ENG&+"+ encodeURI(keywordsStr) + "&x=11&y=4";
    window.location = cmd;
<form name="form1" method="get">
    <input name="keywords" type="text" id="keywords" size="50" >
    <input type="submit" name="btn_search" id="btn_search" value="Search" 
        onClick="javascript:searching(); return false;" onKeyPress="javascript:searching(); return false;">
    <input type="reset" name="btn_reset" id="btn_reset" value="Reset">

This question is tagged with javascript textbox keypress dom-events onkeypress

~ Asked on 2012-12-21 09:18:33

The Best Answer is


Form approach

As scoota269 says, you should use onSubmit instead, cause pressing enter on a textbox will most likey trigger a form submit (if inside a form)

<form action="#" onsubmit="handle">
    <input type="text" name="txt" />

    function handle(e){
        e.preventDefault(); // Otherwise the form will be submitted

        alert("FORM WAS SUBMITTED");

Textbox approach

If you want to have an event on the input-field then you need to make sure your handle() will return false, otherwise the form will get submitted.

<form action="#">
    <input type="text" name="txt" onkeypress="handle(event)" />

    function handle(e){
        if(e.keyCode === 13){
            e.preventDefault(); // Ensure it is only this code that runs

            alert("Enter was pressed was presses");

~ Answered on 2012-12-21 09:42:19


Use onkeypress . Check if the pressed key is enter (keyCode = 13). if yes, call the searching() function.


<input name="keywords" type="text" id="keywords" size="50"  onkeypress="handleKeyPress(event)">


function handleKeyPress(e){
 var key=e.keyCode || e.which;
  if (key==13){

Here is a snippet showing it in action:

document.getElementById("msg1").innerHTML = "Default";_x000D_
function handle(e){_x000D_
 document.getElementById("msg1").innerHTML = "Trigger";_x000D_
 var key=e.keyCode || e.which;_x000D_
  if (key==13){_x000D_
     document.getElementById("msg1").innerHTML = "HELLO!";_x000D_
<input type="text" name="box22" value="please" onkeypress="handle(event)"/>_x000D_
<div id="msg1"></div>

~ Answered on 2012-12-21 09:22:48

Most Viewed Questions: