如何防止WebKit浏览器在输入时按Enter键提交表单 [英] How can I prevent WebKit browser to submit a form when enter is pressed in an input

查看:122
本文介绍了如何防止WebKit浏览器在输入时按Enter键提交表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



请参阅此示例代码:

 < html> 
< body>
< form method =POSTaction =。>
< ul>
< li>< input type =textname =foovalue =<?= rand()?>/>< / li>
< li>< input type =textname =barvalue =<?= $ _ POST ['foo']?>/>< / li>
< / ul>
< / form>
< / body>
< / html>

当按下两个文本输入元素中的任意一个时,提交表单。



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

收听 onsubmit 事件并返回 false


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.

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.

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.

解决方案

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

这篇关于如何防止WebKit浏览器在输入时按Enter键提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆