jQuery Modal that appears on form submit

2019-02-28 16:49发布

问题:

I have this code that I run when a user submits a form (this is to stop them resubmitting the form or leaving the page and let them know that the form is doing something)

var lastx = 0;

var loadingAnim = setInterval(function () { UpdateSpinner("#loading", 128, 1536); }, 32);

function UpdateSpinner(target, step, width)
{
    $(target).css("background-position", lastx + "px 0px");
    lastx = (lastx - step) % width;
}

var objModal = '<div id="overlay"><div id="loading">loading...</div></div>';

function ShowModal()
{
    jQuery('body').append(objModal);
}

$('form').submit(function() { ShowModal(); });

Now this all works fine, except that when a user tries to submit a form that hasn't been filled out correctly I use the jQuery Validation plugin to show them messages BUT the modal will still appear. So my question is how to show the modal but only if NO validation errors have occurred?

Here is an example of my validation code:

$(function() {
    $("#postform").validate({
        rules: {
            post_title: "required",
            post_url: {
                required: {
                    depends: function() {
                        return $('input[name=post_category]:checked').val() == '14';
                    }
                },
                url: true
            },
            post_code: {
                required: {
                    depends: function() {
                        return $('input[name=post_category]:checked').val() == '13';
                    }
                }
            },
            post_content: "required",
            post_tags: "required"
        },
        messages: {
            post_title: "Your post MUST have a title",
            post_url: "Please enter a valid URL, don't forget the http://",
            post_code: "Please add your code",
            post_content: "Your post MUST have some content",
            post_tags: "Please add some tags"
        }
    });
});

I was thinking of maybe using something like this:

function HideModal()
{
    jQuery('body').remove(objModal);
}

that could be run if the validation errors run? Or would there be a much better way to do this? Thanks.

回答1:

numberOfInvalids() should work:

var $validator = {};

$(function() {
    $validator = $("#postform").validate({

        // yada yada validate stuff

    });
});

function ShowModal()
{
    jQuery('body').append(objModal);
}

function HideModal()
{
    jQuery('body').remove(objModal);
}

$('form').submit(function() {
    if ($validator.numberOfInvalids() > 0) {
        HideModal();
    } else {
        ShowModal();
    }
});

Not sure if that is the right order with Hide/ShowModal(), so you may have to switch those. Also, technically you're not hiding and showing, but adding and removing.