防止按 Enter 键提交表单 [英] Prevent form submission on Enter key press
问题描述
我有一个表单
,其中包含两个文本框、一个选择下拉菜单和一个单选按钮.当按下 enter 键时,我想调用我的 JavaScript 函数,但是当我按下它时,form
被提交.
I have a form
with two text boxes, one select drop down and one radio button. When the enter key is pressed, I want to call my JavaScript function, but when I press it, the form
is submitted.
当按下回车键时,如何防止form
被提交?
推荐答案
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)" />
为了在按下回车键时从这个文本框中运行一些用户定义"脚本,而不是让它提交表单,这里有一些示例代码.请注意,此功能不进行任何错误检查,而且很可能只能在 IE 中使用.要正确地做到这一点,您需要一个更强大的解决方案,但您将了解总体思路.
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.
有人指出 keyCode
是 现已弃用.下一个最佳选择 which
也有 已弃用.
It's been pointed out that keyCode
is now deprecated. The next best alternative which
has also been deprecated.
不幸的是,现代浏览器广泛支持的受欢迎的标准 key
有一些 IE 和 Edge 中的狡猾行为.任何早于 IE11 的东西仍然需要 polyfill.
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.
此外,虽然已弃用的警告对于 keyCode
和 which
来说是非常不祥的,但删除它们将代表对无数遗留网站的巨大破坏性变化.出于这个原因,他们不太可能很快就会去任何地方.
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.
这篇关于防止按 Enter 键提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!