简体   繁体   English

即使JavaScript乐趣返回false,也将提交表单

[英]Form gets submitted even if JavaScript fun returns false

Pls check code .html form gets submitted even if javascript returns false. 即使JavaScript返回false,也请提交检查代码.html表单。

<form id="form1" name="form1"   method="post" action="sub.jsp" onsubmit="return getValue()">
<input type="text" id="userName" name="userName"   onkeyup="return getValue()" />
<input type="submit" name="Submit" value="Submit" />
</form>

    <script type="text/javascript" >
    function getValue()
      {
        var userName=document.getElementById("userName");
            document.getElementById("userNamemsg").innerHTML="";
              if(userName.value=="")
              {
             var mdiv=document.getElementById("userNamemsg");
                  mdiv.innerHTML="Error:Required Fields cannot be blank!";
                  form.userName.focus();
                  return false;
               }
              return true;   
     } 

1) try changing line form.userName.focus(); 1)尝试更改line form.userName.focus(); to document.form1.userName.focus(); document.form1.userName.focus();

OR 要么

2) try submitting from function itself: 2)尝试从函数本身提交:

<input type="button" name="Submit" value="Submit" onclick="getValue()" />

<script type="text/javascript" >
function getValue()
  {
        var userName=document.getElementById("userName");
        document.getElementById("userNamemsg").innerHTML="";
          if(userName.value=="")
          {
              var mdiv=document.getElementById("userNamemsg");
              mdiv.innerHTML="Error:Required Fields cannot be blank!";
              document.form1.userName.focus();//I think this is the problem
              return false;
           }
          document.form1.submit();
 }
 </script>

I think there are errors in your JavaScript code that happen prior to your return statements. 我认为您的JavaScript代码中有一些错误在返回语句之前发生。 Fix those errors and your code should work. 解决这些错误,您的代码应该可以工作。

或者,使提交按钮上的单击处理程序返回false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM