jQuery 仅在 _some 字段上通过 Enter 键禁用表单提交
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2794017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Disable form submission via Enter key on only _some fields
提问by justSteve
I want to retain the conventional 'form submits when i press Enter' behavior because users are familiar with. But by reflex, they often hit enter when they finish with a text input box - but before they are actually done with the complete form.
我想保留传统的“按 Enter 时提交表单”行为,因为用户很熟悉。但是反射性地,他们经常在完成文本输入框时按 Enter 键 - 但在他们实际完成完整表单之前。
I'd like to hiHyman the Enter key only when then focus is on a certain class of input.
我想劫持 Enter 键只有当焦点在某一类输入上时。
Looking Related Questionsthis looks like what I'm looking for:
寻找 相关问题这看起来像我正在寻找的:
if (document.addEventListener) {
document.getElementById('strip').addEventListener('keypress',HandleKeyPress,false);
} else {
document.getElementById('strip').onkeypress = HandleKeyPress;
}
but the if (document.addEventListener) {
part is unfamiliar to me.
但这if (document.addEventListener) {
部分对我来说并不熟悉。
回答by Nick Craver
You can capture and cancel the enter keypress
on those fields like this:
您可以keypress
像这样捕获和取消对这些字段的输入:
$('.noEnterSubmit').keypress(function(e){
if ( e.which == 13 ) return false;
//or...
if ( e.which == 13 ) e.preventDefault();
});
Then on your inputs just give them a class="noEnterSubmit"
:)
然后在你的输入上给他们一个class="noEnterSubmit"
:)
Looking ahead in case others find this later, in jQuery 1.4.3(not out yet) you can shorten it to this:
展望未来,以防其他人稍后发现这一点,在jQuery 1.4.3(尚未发布)中,您可以将其缩短为:
$('.noEnterSubmit').bind('keypress', false);
回答by Kailas Mane
Just add following code in <Head>
Tag in your HTML Code.
It will Form submission on Enter Key For all fields on form
只需<Head>
在 HTML 代码的 Tag 中添加以下代码。它将在 Enter Key 上提交表单 对于表单上的所有字段
<script type="text/javascript">
function stopEnterKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type == "text")) { return false; }
}
document.onkeypress = stopEnterKey;
</script>
回答by stackuser
<input type="text" onkeydown="return (event.keyCode!=13);" />
回答by Silas Palmer
To allow enter only on a specific class (in this example, 'enterSubmit'):
仅允许在特定类上输入(在本例中为“enterSubmit”):
jQuery(document).ready(function(){
jQuery('input').keypress(function(event){
var enterOkClass = jQuery(this).attr('class');
if (event.which == 13 && enterOkClass != 'enterSubmit') {
event.preventDefault();
return false;
}
});
});