Question

i got a jquery function that controls that all the required fields of my form are filled and it cancels submission if one of the required fields are empty.

Canceling the form submission works fine, problem is that when i submit my form after a failed submission it stills cancels the form submission, when it should allow the submit because all the form is filled correctly, here is the code:

-Cancel is a bool that indicates if all the form fields are filled.

    if (cancel) 
    {
        $('#form_login').submit(function () 
        { 
            return false;   
        }); 
    }
    else
    {

        $('#form_login').submit(function () 
        { 
            return true;
        }); 
    };

what am i doing wrong ??

thanks

Was it helpful?

Solution

You better call your validation code from within the submit method. For example, a method that does some validation and return true or false. You can return that value as the submit method return value.

For example:

$('#form_login').submit(function ()  
{  
   return isMyFormValid();    
});

function isMyFormValid(){
  //return true or false depending on some conditions.
}

OTHER TIPS

if(cancel) {
   $('#form_login').submit();
} else {
  return false;
}

The problem is that you are attaching a function to the form's submit event multiple times. The first time, when validation fails, the return false; method is attached, and this function is then called each time the form is submitted, even if you attach another function later (when validation succeeds).

What you want to do is:

$('#form_login').submit(function() {
    //define the value of 'cancel' here
    return cancel;
}

If you have already attached a function to the submit event and want to override it, you must first remove the function already attached:

$('#form_login').off('submit');

and then attach the new function.

How about trying what the api suggests:

$('#form_login').submit(function () 
{ 
        if (cancel) {return false;} 
        return true;    
}); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top