IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    表单中只有一个文本框时,回车导致页面刷新

    zongyan86发表于 2015-10-29 07:47:48
    love 0

    如果一个form标签中只有文本框<input type="text" />,当在输入完数据后点击回车,会发现页面进行了刷新,代码如下:

    Html代码  
    1. <body>      
    2.         <form>  
    3.             <input type="hidden" id="contextPath" name="contextPath" value="<%=request.getContextPath()%>" />  
    4.             <textarea rows="2" cols="2" name="test"></textarea>  
    5.             <input type="text" name="noticeNo" id="noticeNo"/>  
    6.         </form>         
    7. </body>  

    有如下解决方法:

    1.在文本域元素中加入onkeydown或者onkeypress事件,判断如果用户点击了回车就阻止默认的行为。

    Java代码  
    1. <body>          
    2.         <form>  
    3.             <input type="textsdfsd" name="noticeNo"  onkeypress="if(event.keyCode==13||event.which==13){return false;}" />      
    4.         </form>  
    5. </body>  

     

    2.在form中在加入一个隐藏的文本域

    <input type="text" name="test" style="display:none"/>

    Html代码  
    1. <body>      
    2.         <form>  
    3.             <input type="hidden" id="contextPath" name="contextPath" value="<%=request.getContextPath()%>" />  
    4.             <textarea rows="2" cols="2" name="test"></textarea>  
    5.             <input type="text" name="noticeNo" id="noticeNo"/>  
    6.             <input type="text" name="test" style="display:none"/>  
    7.         </form>         
    8. </body>  

     说明:大家可以发现,里面是没有提交按钮的即

    <input type="sumit" />,要是里面有提交按钮的话,第二种方法时不使用的,只能使用第一种方法,因为通过查看你会发现,当你点击一个表单时,或者表单的任何元素会发现,提交按钮时激活状态,所以单点击回车时就执行了提交操作。

    web开发分享

    声明: 本文采用 BY-NC-SA 协议进行授权 | WEB开发分享
    转载请注明转自《表单中只有一个文本框时,回车导致页面刷新》



沪ICP备19023445号-2号
友情链接