即使JavaScript fun返回false,表单也会被提交

时间:2009-09-13 04:23:57

标签: javascript jsp submit

请检查代码.html表单即使javascript返回false也会被提交。

<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;   
     } 

3 个答案:

答案 0 :(得分:3)

1)尝试将 form.userName.focus(); 行更改为 document.form1.userName.focus();

OR

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>

答案 1 :(得分:1)

我认为您的JavaScript代码中有错误发生在返回语句之前。修复这些错误,您的代码应该可以正常工作。

答案 2 :(得分:-1)

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

相关问题