Justin
Justin

Reputation: 10897

Can I get the collective result of multiple .submit() handlers?

I have a form that has multiple .submit validations. I would like to register a handler that can do something if the collective result was false.

Here is a very simple snippet that illustrates what I would like to do...

$("#myForm").submit(function() {
    if (conditionA)
    {
        return true;
    }
    else {
        return false;
    }
});

$("#myForm").submit(function() {
    if (conditionB)
    {
        return true;
    }
    else {
        return false;
    }
});

    // TODO: Have some event here that knows if Collective result of .submit was true or false
    $("#myForm").submitParentHandler(function (collectiveResult) {
        if (collectiveResult) {
            alert("Form will be submitted");
        }
        else {
            alert("Form will NOT be submitted");
        }
    });

Where the last method there is currently just an mocked up example of what I would like.

Upvotes: 2

Views: 364

Answers (1)

Tejs
Tejs

Reputation: 41246

I think you just need to rearchitect the solution. Instead of registering multiple submit handlers, instead register methods that contain validation logic like so:

 var submitHandlers = [];

 $('#myForm').submit(function()
 {
      var isValid = true;
      $(submitHandlers).each(function()
      {
           isValid = isValid && this();
      });

      return isValid;
 });

Then you would simply register validation methods to invoke:

submitHandlers.push(function()
{
      return conditionA;
});

submitHandlers.push(function()
{
     return conditionB;
});

When you click submit, it would run through all the methods in submitHandlers and if they all returned true, you would continue. If any returned false, you would return false from the submit handler.

Upvotes: 4

Related Questions