form表单自动提交

时间:2023-08-05 12:16:26

form表单提交是web项目中经常遇到的,但是如果form中只有一个input为text类型的输入框时,

需要格外注意,因为这时候只要你按下回车键,form表单就会自动提交,这是form表单的一个特性。

如何有效的防止呢?

小编认为最简洁有效的方法就是增加一个隐藏域。比如下面的代码就可以解决问题:  

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="../index/login.do" method="post" >
<label for="files">用户名:</label>
<input type="text" name="userName">
<input type="text" style="display: none;">
<button type="submit">提交</button>
</form>
</body>
</body>
</html>

但是这也有个bug就是如果input框获取了焦点,但是未输入任何字符的情况下,点击回车键依旧可以提交表单。因此接下来的这种方法则规避了这一个BUG


第二种方案,就是在input为text的文本框中,增加onkeydown事件,并且当按键是回车键也就是keyCode=13时,不做处理,代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="../index/login.do" method="post">
<label for="files">用户名:</label>
<input type="text" name="userName" onkeydown="if(event.keyCode==13){return false}">
<!-- <input type="text" style="display: none;"> -->
<button type="submit">提交</button>
</form>
</body>
</body>
</html>

以上是小编在实际过程中测试的代码,如有问题,欢迎留言交流!