开发者

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

开发者 https://www.devze.com 2023-04-05 15:54 出处:网络
I have a form th开发者_Python百科at has multiple .submit validations.I would like to register a handler that can do something if the collective result was false.

I have a form th开发者_Python百科at 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消