idris
idris

Reputation: 1049

Can't return form submit to false

So I have a form, and if the input is invalid, I won't let the form pass like so

$(".main-form").submit(function(e){
   return false;
});

This won't let the form pass. When the user complete everything correctly I try to do this

$(".main-form").submit(function(e){
   return true;
});

But for some reason it stays false all the way though. Any workarounds?

Upvotes: 1

Views: 53

Answers (2)

Barmar
Barmar

Reputation: 782785

You should use a single submit handler:

$(".main-form").submit() {
    if (...) {
        return true;
    } else {
        return false;
    }
}

where ... contains your validation checks. The actual code might be somewhat more complex, e.g.

    if (field1 is invalid) {
        return false;
    } else if (field2 is invalid) {
        return false;
    } 
        ...
    } else {
        return true;
    }

Upvotes: 3

dave
dave

Reputation: 64725

You have to clear the old handler, so you'd initialize it like this:

$(".main-form").on('submit', function(e){
    return false;
});

Then to change the handler:

$(".main-form").off('submit');
$(".main-form").on('submit', function(e){
   return true;
});

Upvotes: 0

Related Questions