Form表单中回车后自动提交问题解决方案
1. 问题来源
当form表单中只有一个<input type="text" name="name" />
时按回车键将会自动将表单提交。
<form id="form1" action="post.php" method="post">
<input type="text" name="name" />
</form>
2. 方法一
添加一个隐藏的input标签
<input style="display: none;" type="text" />
3. 方法二
添加一个onkeydown事件,然后回车之后也不会显示
<form id="form1" action="post.php" method="post">
<input type="text" name="name" onkeydown="if(event.keyCode==13) return false;"/>
</form>
但是有些时候,我们需要回车后提交表单,但是这个回车事件应该是可控的,那么可以按照下面的代码操作
<form id="form1" action="post.php" method="post">
<input style="display:none" />
<input type="text" name="name" onkeydown="if(event.keyCode==13){gosubmit();}" />
</form>
gosubmit()中判断表单完整性,决定是否提交表单
我们有时候希望回车键敲在文本框(input element)里来提交表单(form),但有时候又不希望如此。比如搜索行为,希望输入完关键词之后直接按回车键立即提交表单,而有些复杂表单,可能要避免回车键误操作在未完成表单填写的时候就触发了表单提交。
要控制这些行为,不需要借助JS,浏览器已经帮我们做了这些处理,这里总结几条规则:
● 如果表单里有一个type="submit"的按钮,回车键生效。
● 如果表单里只有一个type="text"的input,不管按钮是什么type,回车键生效。
● 如果按钮不是用input,而是用button,并且没有加type,IE下默认为type=button,FX默认为type=submit。
其他表单元素如textarea、select不影响,radio checkbox不影响触发规则,但本身在FX下会响应回车键,在IE下不响应。
type="image"的input,效果等同于type="submit",不知道为什么会设计这样一种type,不推荐使用,应该用CSS添加背景图合适些。
正文到此结束