javascript - returning false not stopping the submission of form -


my purpose: if user field , password field blank, want stop form submitting. code trying:

<!doctype html> <html> <head>     <script>         function doit() {              var usr = document.getelementbyid('ur').value;             var psw = document.getelementbyid('pw').value;              if ((usr.trim() == '') && (psw.trim() == '')) {                 alert("cannot submit form");                 return false;             }          }     </script>  </head>   <body>      <form action="post.php" method="post" onsubmit="doit()">         user:         <input type="text" id="ur" name="user">         <br>         <br> pass:         <input type="password" id="pw" name="pass">         <br>         <br>         <button>submit</button>     </form>   </body> </html> 

i learning javascript. helpful if correct code little explanation why not working.

return false working fine, way calling function wrong.

<form action="post.php" method="post" onsubmit="doit()">  

just calls it, doesn't return value

<form action="post.php" method="post" onsubmit="return doit()">                                                  ^ 

will stop form post on false returned value.

read note on msdn although not ie specific

you can override event returning false in event handler. use capability validate data on client side prevent invalid data being submitted server. if event handler called onsubmit attribute of form object, code must explicitly request return value using return function, , event handler must provide explicit return value each possible code path in event handler function.

now onto important point.

your if condition stop form submission when both fields blank, whereas should if 1 of 2 fields blank. && (and) should || (or), , @ end of functions if nothing returned false, return true then.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -