AJAX No Form Submit On Enter
For an AJAX application I am currently making, I need to check if a user presses enter when typing into an input text field. Usually when enter is pressed, the form is automatically submitted and the page is refreshed. However, when building an AJAX application, the point is to not have page refreshed, and instead to have the enter trigger the AJAX trigger to process the request.
I searched through the web to try and find something that could help me out but couldn't find anything, so decided to write this post in hopes to help other that have the same problem, and since AJAX is turning into the norm on alot of websites lately, this could save people alot of time.
So, the solution.. It's pretty easy actually...
In the form tag, just enter
onsubmit="return false;"
This way, when the form is trying to submit and refresh, the form returns false and doesn't.
Now that gets you through stage one. Now you have to check weather a key that is pressed is the enter key, and if it is the enter key, you need to trigger the AJAX function to work. Here is the enter key form...
function enter_pressed(e){
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return false;
return (keycode == 13);
}
This checks every keypress that is done on a text input, and checks if enter is pressed. Ok, so now that we know if enter is pressed, we need to trigger the AJAX funciton, here we go...
onKeyPress="if(enter_pressed(event)){ search_results('amazon') }"
So we check all key presses, and if our enter_pressed returns true, we trigger the search AJAX function which is search_results. Pretty neat eh?
Comments
Brad posted on 08/27/2007 @ 12:08:30 am
Thanks so much for posting this... you are right, it did save me a bunch of time figuring this all out! Cheers!
pheno posted on 08/19/2007 @ 3:17:27 pm
thnx .. good work



Sven-Ove posted on 09/17/2007 @ 2:22:13 am
Why not use this: