如何防止在基于web的应用程序中按ENTER键提交表单?
当前回答
简单地添加这个属性到你的FORM标签:
onsubmit="return gbCanSubmit;"
然后,在你的SCRIPT标签中,添加这个:
var gbCanSubmit = false;
然后,当你创建一个按钮或出于任何其他原因(比如在函数中)你最终允许提交时,只需翻转全局布尔值并执行.submit()调用,类似于下面的示例:
function submitClick(){
// error handler code goes here and return false if bad data
// okay, proceed...
gbCanSubmit = true;
$('#myform').submit(); // jQuery example
}
其他回答
ENTER键仅仅激活表单的默认提交按钮,这将是第一个
<input type="submit" />
浏览器在表单中查找。
所以不要有提交按钮,而是类似的东西
<input type="button" value="Submit" onclick="submitform()" />
编辑:回应评论中的讨论:
如果只有一个文本字段,这就行不通了——但在这种情况下,这可能是理想的行为。
另一个问题是,这依赖于Javascript来提交表单。从可访问性的角度来看,这可能是一个问题。这可以通过用javascript编写<input type='button'/>来解决,然后在<noscript>标签中放入<input type='submit' />。这种方法的缺点是,对于禁用javascript的浏览器,您将在ENTER时提交表单。在这种情况下,由OP决定期望的行为是什么。
我知道没有办法做到这一点而不调用javascript。
我认为,你可以在javascript的表单中捕获键下,防止冒泡。网页上的ENTER基本上只是提交当前所选控件所在的表单。
//Turn off submit on "Enter" key
$("form").bind("keypress", function (e) {
if (e.keyCode == 13) {
$("#btnSearch").attr('value');
//add more buttons here
return false;
}
});
I Have come across this myself because I have multiple submit buttons with different 'name' values, so that when submitted they do different things on the same php file. The enter / return button breaks this as those values aren't submitted. So I was thinking, does the enter / return button activate the first submit button in the form? That way you could have a 'vanilla' submit button that is either hidden or has a 'name' value that returns the executing php file back to the page with the form in it. Or else a default (hidden) 'name' value that the keypress activates, and the submit buttons overwrite with their own 'name' values. Just a thought.
为了防止在文本区域或输入字段中按enter键时提交表单,请检查submit事件以查找发送该事件的元素类型。
示例1
HTML
<button type="submit" form="my-form">Submit</button>
<form id="my-form">
...
</form>
jQuery
$(document).on('submit', 'form', function(e) {
if (e.delegateTarget.activeElement.type!=="submit") {
e.preventDefault();
}
});
更好的解决方案是,如果没有提交按钮,而使用普通按钮触发事件。这是因为在第一个示例中触发了2个提交事件,而在第二个示例中只触发了1个提交事件。
示例2
HTML
<button type="button" onclick="$('#my-form').submit();">Submit</button>
<form id="my-form">
...
</form>
jQuery
$(document).on('submit', 'form', function(e) {
if (e.delegateTarget.activeElement.localName!=="button") {
e.preventDefault();
}
});