珠峰培训

javascript 回车键触发表单提交的问题

作者:蘑菇点点

2011-07-11 15:14:29

249

 

我们有时候希望回车键敲在文本框(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添加背景图合适些。
实际应用的时候,要让表单响应回车键很容易,保证表单里有个type=”submit”的按钮就行。而当只有一个文本框又不希望响应回车键怎么办呢?我的方法有点别扭,就是再写一个无意义的文本框,隐藏起来。根据第3条规则,我们在用button的时候,尽量显式声明type以使浏览器表现一致。

做了一个 demo(点击查看) 列出了一些例子。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=GBK">
    <title>submit</title>
</head>
<body>
    <h1>本demo演示在文本框中按enter键是否触发提交表单</h1>
    <h2>默认情况下,一个文本框的时候,提交,不管按钮type是submit还是button</h2>
    <form action="http://www.jb51.net/search.asp">
        <input type="text">
        <input type="button" value="提交">
    </form>
    <h2>一个文本框的时候怎么才能做到不提交,方法是加一个隐藏掉的文本框</h2>
    <form action="http://www.jb51.net/search.asp">
        <input type="text">
        <input type="text" style="display:none">
        <input type="button" value="提交">
    </form>
    <h2>只要有type为submit的按钮存在,一个文本框还是多个文本框都提交</h2>
    <form action="http://www.jb51.net/search.asp">
        <input type="text">
        <input type="submit" value="提交">
    </form>
    <h2>只要有type为submit的按钮存在,一个文本框还是多个文本框都提交</h2>
    <form action="http://www.jb51.net/search.asp">
        <input type="text">
        <input type="text">
        <input type="submit" value="提交">
    </form>
    <h2>多个文本框的时候,不提交,用type为button的按钮就行啦</h2>
    <form action="http://www.jb51.net/search.asp">
        <input type="text">
        <input type="text">
        <input type="button" value="提交">
    </form>
    <h2>用button元素时,FX和IE下有不同的表现</h2>
    <form action="http://www.jb51.net/search.asp">
        <input type="text">
        <input type="text">
        <button>提交</button>
    </form>
    <h2>radio和checkbox在FX下也会触发提交表单,在IE下不会</h2>
    <form action="http://www.jb51.net/search.asp">
        <input type="text">
        <input type="radio" name="a">
        <input type="checkbox" name="b">
        <input type="checkbox" name="c">
        <input type="button" value="提交">
    </form>
    <h2>type为image的按钮,等同于type为submit的效果</h2>
    <form action="http://www.jb51.net/search.asp">
        <input type="text">
        <input type="text">
        <input type="image" src="http://www.jb51.net/images/logo.gif">
    </form>
</body>
</html>