简体   繁体   中英

jQuery form Validator: need to submit twice

I am trying to implement the Form Validator from Jquery. onSuccess, I do an ajax-call.

I was wondering why I need to push the submit-button twice before the validation starts working?

The script is in a separate file which is included. If I call $.validation() on the page itself, it works immediately.

Here is the js-code:

$(document).ready(function () {
    $("#frmNews").submit(function (e) {
        e.preventDefault();

        // -- form validation
        $.validate({
            language: nederlands,
            onError: function () {
                // -- show alert
                $("#feedback-error").removeClass('hidden');
                // -- back to top
                $("html, body").animate({scrollTop: 0}, "slow");
            },
            onSuccess: function () {
                // -- show preloader
                $('body').toggleClass('loaded');

                $.ajax({
                    type: 'POST',
                    url: '/ajax',
                    data: $("#frmNews").serialize(),
                    success: function (data) {
                        var result = $.trim(data);
                        if (result == 'success') {
                            // -- show alert
                            $("#feedback-success").removeClass("hidden");
                            // -- clear all fields
                            emptyAllInputFields("#frmNews");
                            // -- back to top
                            $("html, body").animate({scrollTop: 0}, "slow");
                            // -- hide preloader
                            $('body').toggleClass('loaded');
                        }
                        else if (result == 'error_saving') {
                            // -- alert
                            $("#feedback-error").removeClass("hidden");
                            // -- back to top
                            $("html, body").animate({scrollTop: 0}, "slow");
                            // -- hide preloader
                            $('body').toggleClass('loaded');
                        }
                    }
                });
            }
        });
    });
});

As mentioned by @epascarello in the comment section, you should place your validation outside of the submit handler.

What's actually happening in your script - The $.validate() is only initiated once the submit button is pressed. Then it handles validation (and eventually AJAX) on next click.

$("#frmNews").submit(function (e) {
    e.preventDefault();
});

$.validate({
    // ... your validation ...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM