Wednesday, October 20, 2010

enter key submits without javascript

What was absolutely mind boggling to me is when my script had input tags that would work just fine when pressing enter, running the javascript and others that wouldn't. To explain further heres the code that was in the input text tags:
onKeyPress="if(event.keyCode == 13){ search() }"

Here you see the event which is equal to enter (when enter is pressed) should run the function of javascript (in this case search which does... you guessed it, search) anyway the problem was it would submit the form in the get method in the simplest way that my website couldn't interpret because it's a little more complex and sends stuff inside files... to the solution!

add this code to the body tag at the top of the pages with this issue:
OnKeyPress="return disableEnterKey(event)"

and add the function to your general javascript or somewhere at the header depending on how you do things:

function disableEnterKey(e){
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox

return (key != 13);
}


This solved my issue, source and credit for this solution (although with a small misspelling) goes to this link: http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx

2 comments:

Deepak said...

the download link is broken. the page opens ad.fly and when i escape that it says the page no longer exists. please help

theborisedu said...

there's no link on this page, which one are you talking about?