Using the jquery validation plugin on a form that is generated using Ajax

此生再无相见时 提交于 2019-12-20 02:42:26

问题


When using the jQuery validation plugin, how do I validate a form that is generated using ajax?

I mean to ask, the form does not initially appear on the page when the page loads, but is added to the page using ajax.

I'm following the examples on bassistance.de/jquery-plugins/jquery-plugin-validation/, but it seems that the validation plugin will not validate the form. Otherwise, it works fine. Is there a way to do this. Just like jquery uses live(), is there something I can use to make the plugin work in this scenario?

I'm doing things this way:

$("#thisForm").validate({

    rules: {

    },

    messages: {

    },

    submitHandler: function() {
    $.ajax({
            type: "POST",
             url: "/",
            data: $('#thisForm').serialize(),
        dataType: "json",
           cache: false,

        beforeSend: function(html) {

        },

    success: function(signInData) {


        },

        });
    }
});

回答1:


Quote OP:

"... the form does not initially appear on the page when the page loads, but is added to the page using ajax. ... like jquery uses live(), is there something I can use to make the plugin work in this scenario?"

There is no method available to delegate binding the jQuery Validate plugin to a form that has not yet been constructed.

Since .validate() is the initialization method for the plugin, you simply need to call it immediately after you dynamically create this form.

However, you have not shown the code that creates the form, so this example assumes you create the form by clicking something. Adjust this as needed... just keep in mind that you need to make sure the ajax is complete (the new form exists) before calling .validate() to initialize the plugin.

$(document).ready(function() {  // ensure the DOM is ready

    $('#something').on('click', function() { // clicking something to create the form

        $.ajax({  // your ajax code to create the form
            // your ajax options,
            complete: function() { // fires after the ajax is fully complete
                $("#thisForm").validate({ // initialize the plugin on the new form
                    // options & rules
                });
            }
        });

    });

});

complete: - A function to be called when the request finishes (after success and error callbacks are executed).

See: http://api.jquery.com/jQuery.ajax/




回答2:


Try adding DOM delegation with .on() like this

$("body").on("validate", "#thisForm", function() {

});

Edit to address comments below:

If you cannot delegate the event through parent elements, you must bind the event handler after it is placed into the DOM. Here is an example using jQuery:

$("addmyHTMLhere").html('<form></form>').find('form').validate({put your validate stuff here});



回答3:


Ran into the same issue, not sure if there is a better way of doing what you want, but this is what I came up with:

$(document.body).on('submit', '#myform', function(e){

    // Set your validation settings and initialize the validate plugin on the form.
    $(this).validate({
        submitHandler: function(form) {
            // do your ajax submit or whatever you want.
        }
    });

    // submit the form pro grammatically.
    $(this).submit();
});

again maybe there is a better way of doing this, but that is what I figured out to work well so far.




回答4:


I also had this problem when loading the form via AJAX and also wanting to submit the form with AJAX (to stay on current page...). This worked for me:

//Newbie note: ajaxFormCallback is the callback function - which runs once my AJAX loaded form has been added to the page.

var ajaxFormCallback = function(){
    var form = $('#form-id-here');

    form.validate({
        rules: {
            'name': {
                required: true
            },
            'email': {
                required: true,
                email: true
            }
        },
        messages: {
            'name': {
                required: 'Name is required'
            },
            'email': {
                required: 'Email address is required',
                email: 'Invalid email address'
            }
        },
        submitHandler: function(form){
            //submit form via AJAX
            $.ajax({
                type: 'POST',
                url: '/path/to/submit/form/?' + $(form).serialize() + '&ajax=1',
                success: function(data){
                    //replace my form with a response:
                    $(form).parents('.response').replaceWith(data);
                }
            });
        }
    });
};


来源:https://stackoverflow.com/questions/18678869/using-the-jquery-validation-plugin-on-a-form-that-is-generated-using-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!