简体   繁体   中英

JQuery cannot validate a form that was called from an external HTML file

My imported form will not validate using JQuery's $(form).validate() plugin.

I followed the example provided from this question and got the form working successfully. I moved my form to /html/external.html (I like to keep my main site in one file, index.php , and all my external forms/elements in a separate one), and calling the validation function did not work.

function validateForm() {
    $('#registerForm').validate({
        //rules
        ...

        submitHandler: function(form) {
            $.ajax({
                type: 'POST',
                url: url,
                data: $(form).serialize(), // Fixed typo
                success: function () {
                    alert('succss')
                }
            })
            return false;
        }
    })
}

$(document).ready(function() {
    validateForm() // Validating the form on page load
})

$(document).on('click', '.toFormScreen', function() {
    $('#welcome').remove() // Yes, #welcome was imported as well if the user was not logged in
    $('#mainContainer').load('./html/external.html #registerForm')
    validateForm();
})

The above does not work, because it cannot find the form element, being in a different file that's not imported on page load.

I tried adding the validation function below the load: validateForm() and that still doesn't work.

Is it possible to $(e).validate({...}) a form that has been imported/appended by a user at any given time after the page loads from an external HTML file?

EDIT: https://jqueryvalidation.org/ is the plugin I'm using.

The issue is because load() is asynchronous. Therefore you're instantiating validate() on #registerForm before it has been created in the DOM.

To fix this you need to place the call to validateForm within the callback of load() :

$(document).on('click', '.toFormScreen', function() {
  $('#welcome').remove()
  $('#mainContainer').load('./html/external.html #registerForm', function() {
    validateForm();
  });
})

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