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.
How do I prevent the form
from being submitted when the enter key is pressed?
if(characterCode == 13) {
// returning false will prevent the event from bubbling up.
return false;
} else{
return true;
}
好的,假设您的表单中有以下文本框:
<input id="scriptBox" type="text" onkeypress="return runScript(event)" />
为了在按下回车键时从此文本框中运行一些“用户定义”脚本,并且不让它提交表单,这里有一些sample代码。请注意,此函数不执行任何错误检查,并且很可能仅在 IE 中工作。为了正确地做到这一点,您需要一个更强大的解决方案,但您将获得总体思路。
function runScript(e) {
//See notes about 'which' and 'key'
if (e.keyCode == 13) {
var tb = document.getElementById("scriptBox");
eval(tb.value);
return false;
}
}
返回函数的值将提醒事件处理程序不要进一步冒泡该事件,并将阻止进一步处理按键事件。
NOTE:
有人指出keyCode
is 现已弃用。下一个最佳选择which
has 也已被弃用.
不幸的是,受欢迎的标准key
,被现代浏览器广泛支持,有一些IE 和 Edge 中的狡猾行为。任何早于 IE11 的版本仍需要polyfill.
此外,虽然已弃用的警告是相当不祥的keyCode
and which
,删除这些内容将意味着对无数遗留网站的巨大破坏性改变。是因为,他们不太可能很快就去任何地方。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)