按键盘enter键触发提交submit按钮

要实现功能:在input框中输入text后直接按enter也可提交表单

示例如下:

1、html页面

<form id="fm" action="#" name="ThisForm" method="post">
  <TABLE border="0" cellSpacing="0" cellPadding="0" width="100%">
      <TR>
          <TD style="HEIGHT:18px"><span id="msg" style="color:red;font-size:15px">${msg}</span></TD>
      </TR>
      <TR>
          <TD style="HEIGHT: 30px">
              <span style="font-family: 微软雅黑;font-size: 13px;">账号:</span>
              <INPUT type="text" id="userName" name="userName" style="width: 110px;">
          </TD>
      </TR>
      <TR>
          <TD style="HEIGHT: 30px">
              <span style="font-family: 微软雅黑;font-size: 13px;"> 密码:</span>
              <INPUT type="password" id="userPw" name="userPw" style="width:110px;">
          </TD>
      </TR>
      <TR>
          <TD style="HEIGHT: 50px"> 
              <input type="button" id="loginBtn" value="登陆" style="width: 80px;" onclick='check1()'>
              <img id="indicator" src="/${pageContext.request.contextPath}/images/loading.gif" style="display:none"/>
          </TD>
      </TR>   

  </TABLE>
</form>

2、js脚本

<script>
function check1(){
    //获取账户,密码,做非空校验
    var username=$("#userName").val();
    var password=$("#userPw").val();
    var um=$.trim(username);
    var up=$.trim(password);
    if(null==um||""==um){
        alert("请输入账户信息");
        return;
    }
    if(null==up||""==up){
        alert("请输入密码信息");
        return;
    }
    //判断用户选择的类型
    if(document.ThisForm.userType.value=="0"){
        //向管理员模块进行提交
        document.getElementById("fm").action="${pageContext.request.contextPath}/AdminServlet?method=adminLogin";
    }
        
    if(document.ThisForm.userType.value=="1"){
        //向老师模块进行提交
        document.getElementById("fm").action="${pageContext.request.contextPath}/TeacherServlet?method=teacherLogin";
    }
    document.getElementById("fm").submit();
    
}
//页面加载完毕
$(function(){
    //按键盘enter键触发提交按钮
      $('#userPw').focus(function(){
            document.onkeydown = function (event) {
                if (event && event.keyCode == 13) {
                    $("#loginBtn").click();
                }
            }
        });
    
});
</script>  

 

 

 

posted @ 2019-12-01 16:40  timetellu  阅读(1982)  评论(0编辑  收藏  举报