开发者

jQuery Modal that appears on form submit

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 c开发者_开发知识库ontent",
            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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜