HTML防止input回车提交表单

276次阅读
没有评论

当 form 表单中,存在一个 button,在 input 中按回车会自动触发 form 提交,很是郁闷,经过查询资料,特总结如下:

自动提交情况说明:

1. 默认情况下,单个输入框,无论按钮的 type=”submit” 还是 type=”button” 类型,回车即提交。
2. 当 type=”submit” 时,无论有几个 type=”text” 输入框,回车均表示提交。(<button> 按钮默认的 type 为 submit)
3. 当 type=”button” 时,且存在多个输入框,回车不提交。(button)

解决方案:
1. 解决单个输入框的回车即提交问题,可以增加一个隐藏的 input=”text” display=’none’; 然后 type 类型为 button。
2. 在 form 表单或 input 中加入:onkeydown=”if(event.keyCode==13){return false;}”
实例一:

<!-- enter 会自动提交数据 -->
<form action="www.baidu.com" method="post">
    <input type="text" value="" />
    <input type="text" value="" />
    <button> 提交 </button>
    <!-- 等价于 <button type="submit"> 提交 </button> 或 <input type='submit' value='提交'>-->
</form>

实例二:

 <!-- enter 不会自动提交数据 -->
<form action="www.baidu.com" method="post">
    <input type="text" value="" />
    <input type="text" value="" />
    <button type="button"> 提交 </button>
    <!-- 等价于 <input type='button' value='提交'> -->
</form>

实例三:

<!-- enter 不会自动提交数据 -->
<form action="www.baidu.com" method="post" onkeydown="if(event.keyCode==13){return false;}">
<input type="text" value="" />
<input type="text" value="" />
<button> 提交 </button>   
 
<!-- 或在对应 input 上添加,同时建议取消自动填充,因为 mac 下会有问题
<input type="text" value=""autocomplete="off"onkeydown="if(event.keyCode==13){return false;}" />
 -->

</form>
正文完
有偿技术支持加微信
post-qrcode
 
评论(没有评论)
验证码