Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling the "Enter" / "Return" key in Chrome

Tags:

javascript

I have an AJAX-y type page. When the user clicks "GO" I need to execute a specific javascript function. I also want to simulate the "GO" click when a user hits "Enter" or "Return. Please note that I do not want to "submit" the page. The reason why is because i am doing everything via JavaScript.

To handle the "Enter" / "Return" key press in IE and FireFox, I am using the following code:

$(document).ready(function () {  
  $('#root').keypress(function(e) { 
    if (e.keyCode == '13') { 
      goButton(); 
    } 
  });
});

Unfortunately, this code is not working in Chrome. The goButton() function gets called. The problem though is the page gets submitted. What am I doing wrong?

like image 863
Villager Avatar asked Aug 16 '10 20:08

Villager


People also ask

Why does my enter key not work in Chrome?

According to users, if your keyboard isn't working in Chrome, you might be able to fix the problem simply by resetting it to default. Sometimes your Chrome profile can get corrupted, or an extension can interfere with it. To fix the problem, reset Chrome to the default and check if that helps.

What is the shortcut to go back a page in Chrome?

Goes to the previous page in your browsing history for the tab. Press Backspace , or Alt and the left arrow together.


2 Answers

Assuming you have a form:

$('#theForm').submit(function(e){
    e.preventDefault();
    goButton();
    return false; // just to be sure.
});

You need to prevent the submit event from the form, which gets called when the form has focus and a user presses enter.

like image 173
BGerrissen Avatar answered Oct 04 '22 11:10

BGerrissen


I agree with BGerrissen, that is the best approach. However, to better adapt to your code you can just add the stops to your current function:

$(document).ready(function () {  
  $('#root').keypress(function(e) { 
    if (e.keyCode == '13') { 
      e.preventDefault();//Stops the default action for the key pressed
      goButton(); 
      return false;//extra caution, may not be necessary
    } 
  });
});
like image 44
UpHelix Avatar answered Oct 04 '22 10:10

UpHelix