如何在输入中按下输入时,如何阻止WebKit浏览器提交表单[重复]

时间:2022-11-23 21:50:32

This question already has an answer here:

这个问题在这里已有答案:

When using a form with many text input, WebKit/Safari/Google Chrome submits the form when ''enter'' is pressed in any input element. Even if there is no submit input element and no onclick handler registered.

当使用具有许多文本输入的表单时,当在任何输入元素中按下“输入”时,WebKit / Safari / Google Chrome会提交表单。即使没有提交输入元素也没有注册onclick处理程序。

See for instance this sample code:

例如,请参阅此示例代码:

<html>
    <body>
        <form method="POST" action=".">
            <ul>
                <li><input type="text" name="foo" value="<?=rand()?>"/></li>
                <li><input type="text" name="bar" value="<?=$_POST['foo']?>"/></li>
            </ul>
        </form>
    </body>
</html>

When pressing enter in any of the two text input elements, the form is submitted.

当在两个文本输入元素中的任何一个中按Enter键时,将提交表单。

Since I'm handling my form in JavaScript with asynchronous HTTP requests, I need to prevent this behavior. I could register a custom handler for the keypressed event to preventDefault and stopPropagation . But its seems ugly and is not really practical when new text input elements are added dynamically.

由于我在JavaScript中使用异步HTTP请求处理我的表单,因此我需要阻止此行为。我可以为keypressed事件注册一个自定义处理程序来阻止默认和stopPropagation。但它看起来很丑陋,并且在动态添加新的文本输入元素时并不实用。

3 个解决方案

#1


Listen for the onsubmit event on the form and return false.

在窗体上侦听onsubmit事件并返回false。

#2


If you don't ever want the form to submit, don't include a <form> element at all. It's valid to include free-standing form field elements.

如果您不希望表单提交,请不要​​包含

元素。包含独立的表单字段元素是有效的。

value="<?=$_POST['foo']?>"

XSS vulnerability. You need to htmlspecialchars() all text-to-HTML output.

XSS漏洞。您需要htmlspecialchars()所有文本到HTML输出。

#3


Daniel A. White is right, but since I got a little bit confused by the answer, maybe it should be clearly stated that the return false should be on the event:

Daniel A. White是对的,但是由于我对答案感到有些困惑,也许应该清楚地说明返回false应该在事件上:

function goWithSubmit(e)
{
  if (e) e.returnValue=false;
}

#1


Listen for the onsubmit event on the form and return false.

在窗体上侦听onsubmit事件并返回false。

#2


If you don't ever want the form to submit, don't include a <form> element at all. It's valid to include free-standing form field elements.

如果您不希望表单提交,请不要​​包含

元素。包含独立的表单字段元素是有效的。

value="<?=$_POST['foo']?>"

XSS vulnerability. You need to htmlspecialchars() all text-to-HTML output.

XSS漏洞。您需要htmlspecialchars()所有文本到HTML输出。

#3


Daniel A. White is right, but since I got a little bit confused by the answer, maybe it should be clearly stated that the return false should be on the event:

Daniel A. White是对的,但是由于我对答案感到有些困惑,也许应该清楚地说明返回false应该在事件上:

function goWithSubmit(e)
{
  if (e) e.returnValue=false;
}