如何防止在基于web的应用程序中按ENTER键提交表单?


当前回答

另一种方法是仅在表单应该提交时才将提交输入按钮附加到表单,并在表单填充期间将其替换为简单的div

其他回答

另一种方法是仅在表单应该提交时才将提交输入按钮附加到表单,并在表单填充期间将其替换为简单的div

这是一个jQuery处理程序,可以用来停止输入提交,也停止退格键->返回。"keyStop"对象中的(keyCode: selectorString)对用于匹配不应该触发默认动作的节点。

记住,网络应该是一个可访问的地方,这打破了键盘用户的期望。也就是说,在我的情况下,我正在工作的web应用程序不喜欢后退按钮,所以禁用它的快捷键是可以的。“应该输入->提交”的讨论很重要,但与实际提出的问题无关。

以下是代码,由您自行考虑可访问性以及为什么要这样做!

$(function(){
 var keyStop = {
   8: ":not(input:text, textarea, input:file, input:password)", // stop backspace = back
   13: "input:text, input:password", // stop enter = submit 

   end: null
 };
 $(document).bind("keydown", function(event){
  var selector = keyStop[event.which];

  if(selector !== undefined && $(event.target).is(selector)) {
      event.preventDefault(); //stop event
  }
  return true;
 });
});

将这个标签添加到你的表单- onsubmit="return false;" 然后只能使用JavaScript函数提交表单。

你会发现这更简单和有用:D

$(document).on('submit', 'form', function(e){
    /* on form submit find the trigger */
    if( $(e.delegateTarget.activeElement).not('input, textarea').length == 0 ){
        /* if the trigger is not between selectors list, return super false */
        e.preventDefault();
        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.