Reputation: 2649
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
Upvotes: 0
Views: 55
Reputation: 207901
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();
Upvotes: 1
Reputation: 634
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;
}
Upvotes: 3