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


当前回答

在过去,我总是用类似上面的按键处理程序来完成它,但今天遇到了一个更简单的解决方案。输入键只是触发表单上第一个未禁用的提交按钮,所以实际上所需要的只是拦截试图提交的按钮:

<form>
  <div style="display: none;">
    <input type="submit" name="prevent-enter-submit" onclick="return false;">
  </div>
  <!-- rest of your form markup -->
</form>

就是这样。按键将像往常一样由浏览器/字段等处理。如果进入-提交逻辑被触发,那么浏览器将找到隐藏的提交按钮并触发它。javascript处理程序会阻止提交。

其他回答

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

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

如果这些答案都不适合你,试试这个。在实际提交表单的按钮之前添加一个提交按钮,对事件什么都不做。

HTML

<!-- The following button is meant to do nothing. This button will catch the "enter" key press and stop it's propagation. -->
<button type="submit" id="EnterKeyIntercepter" style="cursor: auto; outline: transparent;"></button>

JavaScript

$('#EnterKeyIntercepter').click((event) => {
    event.preventDefault(); //The buck stops here.
    /*If you don't know what this if statement does, just delete it.*/
    if (process.env.NODE_ENV !== 'production') {
        console.log("The enter key was pressed and captured by the mighty Enter Key Inceptor (⌐■_■)");
    }
});
//Turn off submit on "Enter" key

$("form").bind("keypress", function (e) {
    if (e.keyCode == 13) {
        $("#btnSearch").attr('value');
        //add more buttons here
        return false;
    }
});

[2012修订版,没有内联处理程序,保留textarea进入处理]

function checkEnter(e){
 e = e || event;
 var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
 return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
}

现在你可以在表单上定义一个按键处理程序: <形式[…onkeypress="return checkEnter(event)">

document.querySelector('form').onkeypress = checkEnter;