Possible Duplicate:
jQuery Event Keypress: Which key was pressed?
OK, here's my situation (I've solved this issue in the past, but since I'm not sure my approach was the best, I'm all ears for some advice) :
- I've got a simple HTML form
- The purpose of this form is NOT to be submitted EVER
- The user normal clicks the (pseudo)
Submit
button, and the desired action is executed (via Javascript/Ajax, etc)
The thing is :
- If the user hits enter, then the form is submitted, something we definitely DON'T WANT.
- What we want is to catch that particular keypress, and in that case, trigger the action that would normally be executed if the button was clicked.
How would you go about this?
My Approach
The Form
<form id="someId" action="#" method="post"
onsubmit="return false;" onkeypress="return enterSub(this,event);">
...
</form>
The Code
function enterSub(inField, e)
{
var charCode;
if(e && e.which)
{
charCode = e.which;
}
else if (window.event)
{
e = window.event;
charCode = e.keyCode;
}
if (charCode == 13)
{
performThatAction; // My Main action
}
}