if(characterCode == 13)
{
return false; // returning false will prevent the event from bubbling up.
}
else
{
return true;
}
Ok, so imagine you have the following textbox in a form:
<input id="scriptBox" type="text" onkeypress="return runScript(event)" />
In order to run some "user defined" script from this text box when the enter key is pressed, and not have it submit the form, here is some sample code. Please note that this function doesn't do any error checking and most likely will only work in IE. To do this right you need a more robust solution, but you will get the general idea.
function runScript(e) {
//See notes about 'which' and 'key'
if (e.keyCode == 13) {
var tb = document.getElementById("scriptBox");
eval(tb.value);
return false;
}
}
returning the value of the function will alert the event handler not to bubble the event any further, and will prevent the keypress event from being handled further.
NOTE:
It's been pointed out that keyCode
is now deprecated. The next best alternative which
has also been deprecated.
Unfortunately the favored standard key
, which is widely supported by modern browsers, has some dodgy behavior in IE and Edge. Anything older than IE11 would still need a polyfill.
Furthermore, while the deprecated warning is quite ominous about keyCode
and which
, removing those would represent a massive breaking change to untold numbers of legacy websites. For that reason, it is unlikely they are going anywhere anytime soon.
Using
<button type="button">Whatever</button>
should do the trick.
The reason is because a button inside a form has its type implicitly set to submit
. As zzzzBoz says, the Spec says that the first button
or input
with type="submit"
is what is triggered in this situation. If you specifically set type="button"
, then it's removed from consideration by the browser.
Best Answer
Theoretically, setting
KeyPreview
property of the form toTrue
should do it. Then handleKeyDown
event, and make sure to sete.Handled
toTrue
on pressing the Enter key (or e.SuppressKeyPress, depends on implementation of controls you are working with).I tried this approach in a sample project just now, however, and it did not work with a button for some reason. You may need to resort to using
WndProc
on the form level, this always works 100%.