2
<form ... onsubmit="return false">
   <input type="text" name="location" ...>
   <input type="url" ... required>
   ...
</form>

Now, if I enter a location and hit ENTER, the browser tells me that an URL is required which is not an expected or desired outcome. The ENTER should just be ignored.


Question

How can I prevent the browser from checking the required field after hitting ENTER in the "location" input field and only let the browser check the "url" field when submitting the form with JavaScript using form.submit()?

4

4 回答 4

2

您需要停止表单元素的输入按钮的默认行为。

举个例子:

HTML5 表单为

<form id="form">
  <input type="text" name="test1" id="test1" required/>
  <input type="text" name="test2" id="test2" required/>
  <input type="submit" value="Test"/>
</form>

然后应用下面的代码

$(document).ready(function() {
  $(form).find('input').on('keydown', function(e){
     if(e.which == 13) // KEY.ENTER = 13
       e.preventDefault();
  });
});

基于上述情况,这里是fiddle

于 2014-03-05T14:35:52.443 回答
1

您可以在表单元素中使用novalidate属性:

<form method="post" action="..." novalidate>...</form>
于 2014-03-05T14:38:14.490 回答
1

这就是我现在所做的并且有效的方法(使用 jQuery,其中 $form 代表 ):

$form.find('input').on('keydown', function(e){
    if(e.which == KEY.ENTER) // KEY.ENTER = 13
        e.preventDefault();
});
于 2014-03-05T14:44:54.783 回答
-2

有一种处理“提交”的特定方法。在这里

于 2014-03-05T17:07:42.103 回答