简体   繁体   中英

JavaScript form submitting when not validating

I'm using the following JS to validate a form when submitting:-

function validate()
{
   if( document.square.PosX.value == "" )
   {
     alert( "Please pick where in the square you think we are" );
     document.myForm.PosX.focus() ;
     return false;
   }
   return true;
}

<form name="square" action="save_results.php" method="post" onsubmit="return validate();">
         <input type="text" id="PosX" name="PosX">
         <input type="submit" value="Submit">
</form>

When the field 'PosX' is empty and I hit Submit I see the alert popup in the browser, but when I click OK the form still submits.

How can I prevent it from actually submitting unless the form fields are not empty?

Thanks

You have a copy&paste error in your script: See the form name: document.square.PosX.focus() ;

function validate()
{
   if( document.square.PosX.value == "" )
   {
     alert( "Please pick where in the square you think we are" );
     document.square.PosX.focus() ;
     return false;
   }
   return true;
}

It's failing because you're referencing a form named myForm when it's actually named square. If you look at the error console when you run the code, you'll see you get Uncaught TypeError: Cannot read property 'PosX' of undefined because of this.

Change the line document.myForm.PosX.focus() ; to document.square.PosX.focus();

jsFiddle example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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