Chris Campbell
Chris Campbell

Reputation: 91

Form still submitting after return false

I have added validation but the form still submits even after the script has returned false

Form Submit

 <form action=payment.php method=POST name=UserForm id=UserForm onsubmit="return check(this);return false;">    

Javascript

 function check(event) {    

 $('input').each(function() {
    if(!$(this).val()){
        alert('Some fields are empty');
       return false;
    }
   });  


   } 

Upvotes: 0

Views: 1023

Answers (2)

Fraser
Fraser

Reputation: 17094

return check(this);return false;

The second return return false is unreachable. Also, the alert statement blocks the return in your other code - and the check function doesn't return anything.

function check(event) {    
 $('input').each(function() {
    if(!$(this).val()){
       alert('Some fields are empty'); //blocking here
       return false; // this isn't the return of the check function
    }
   });  
}

You should do something like

function check(event) {    
   var result = true;
   $('input').each(function() {
    if(!$(this).val()){
       result = false;
    }
   });  

   return result;
}

Upvotes: 0

Sergiu Paraschiv
Sergiu Paraschiv

Reputation: 10163

return false; inside jQuery each won't work. You are returning inside an anonymous function, not inside function check(event). What you need to do is use a flag.

function check(event) {  
    var errorFlag = false;
    $('input').each(function() {

        if(!$(this).val()){
            alert('Some fields are empty');
            errorFlag = true;
        }

    }); 

    return !errorFlag;
}

Upvotes: 4

Related Questions