如何防止在基于web的应用程序中按ENTER键提交表单?
当前回答
你将不得不调用这个函数,它将取消表单的默认提交行为。您可以将它附加到任何输入字段或事件。
function doNothing() {
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if( keyCode == 13 ) {
if(!e) var e = window.event;
e.cancelBubble = true;
e.returnValue = false;
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
其他回答
将这个标签添加到你的表单- onsubmit="return false;" 然后只能使用JavaScript函数提交表单。
我在这里或其他帖子中找到的所有关于这个主题的答案都有一个缺点,那就是它阻止了表单元素上的实际更改触发器。所以如果你运行这些解决方案,onchange事件也不会被触发。为了克服这个问题,我修改了这些代码,并为自己开发了以下代码。我希望这对其他人有用。 我给了一个类我的表单“prevent_auto_submit”,并添加以下JavaScript:
$(document).ready(function()
{
$('form.prevent_auto_submit input,form.prevent_auto_submit select').keypress(function(event)
{
if (event.keyCode == 13)
{
event.preventDefault();
$(this).trigger("change");
}
});
});
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.
我认为,你可以在javascript的表单中捕获键下,防止冒泡。网页上的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
}