views:

305

answers:

3

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;   
     }
+1  A: 

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

David Andres
+1 unspecific answer but it's true: in a function like onsubmit or onclick, if your JavaScript errors out, the form will be submitted or link followed anyway. If you haven't turned on the error box on script errors, it can be unclear what has happened.
bobince
+3  A: 

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>
TheVillageIdiot
document.form1 worked. Thanks.
Chava
A: 

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

Here Be Wolves