Question

Pls check code .html form gets submitted even if javascript returns 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;   
     } 
Was it helpful?

Solution

1) try changing line form.userName.focus(); to document.form1.userName.focus();

OR

2) try submitting from function itself:

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

OTHER TIPS

I think there are errors in your JavaScript code that happen prior to your return statements. Fix those errors and your code should work.

alternatively, you make the click handler on the submit button to return false.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top