Maison  >  Article  >  interface Web  >  form表单按回车键提交处理方法

form表单按回车键提交处理方法

巴扎黑
巴扎黑original
2016-11-25 14:29:471295parcourir

1、当form表单中只有一个a37eeb83c9e5f0db35939ae96af259e6时按回车键将会自动将表单提交。

Html代码  

<form id=&#39;form1&#39; action=&#39;a1.jsp&#39; method=&#39;post&#39;>  
<input type=&#39;text&#39; name=&#39;name&#39; />  
</form>

 再添加一个5405ec19f1d2c7c9609565a405b3e7ac按下回车将不会自动提交,但是页面上显示一个不知所云的输入框挺别扭,后从网上搜到两个解决办法:

  1;添加一个04a82fd019edce04d49e579a0db0f5a5不显示输入框,然后回车之后也不会提交:

Html代码  

<form id=&#39;form1&#39; action=&#39;a1.jsp&#39; method=&#39;post&#39;>  
<input type=&#39;text&#39; name=&#39;name&#39; />  
<input style=&#39;display:none&#39; />  
</form>

 2;添加一个onkeydown事件,然后回车之后也不会显示:

Html代码  

<form id=&#39;form1&#39; action=&#39;a1.jsp&#39; method=&#39;post&#39;>  
<input type=&#39;text&#39; name=&#39;name&#39; onkeydown=&#39;if(event.keyCode==13) return false;&#39;/>  
</form>

 如果想添加回车事件可以在onkeydown事件中添加判断提交表单:

Html代码  

<form id=&#39;form1&#39; action=&#39;a1.jsp&#39; method=&#39;post&#39;>  
<input style=&#39;display:none&#39; />  
<input type=&#39;text&#39; name=&#39;name&#39; onkeydown="onKeyQuery(event);" />  
</form>

 

Js代码  

//回车查询  
   function onKeyQuery(e){  
       if(window.event) // IE  
       {  
           keynum = e.keyCode  
       }  
       else if(e.which) // Netscape/Firefox/Opera  
       {  
           keynum = e.which  
       }  
       if(keynum == 13){  //等于13代表 回车键  
           //具体处理在这里  
       }  
   }

 

 我们有时候希望回车键敲在文本框(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添加背景图合适些。


Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn