jQuery Validate not working with Ajax and jQuery dialog

734 views Asked by At

On my website I have a navigation and a main content area. When you click on a navigation link, the content inside the main content area always gets loaded via ajax. If you click the link "Contact", a text gets loaded which contains a link for a jQuery dialog which contains the contact form.

The problem: When you load the website and navigate to the contact form area, the validation works perfectly fine. However, if you navgiate away to another content area (= another content gets loaded via ajax) and then go back to the contact form area and click the submit button (WITHOUT reloading the page in between), validation fails, gets ignored and the form action gets executed. If you reload the page and then navigate to the contact form area, everything works again.

I cannot make sense of this behaviour. What is weird: Validating another form in the content area which is NOT opened in a jQuery dialog always works, no matter what you had clicked before. So it must be because of the jQuery dialog popup and Ajax. Who can make sense of this problem?

Here comes my code:

HTML:

<a href="#popup-form-test" id="open-popup-form-test">open form test popup</a>

<div id="popup-form-test">
    <form id="form-test" action="somelink">
        <input type="text" placeholder="testtext eingeben" name="testText"></input>
        <input type="submit" value="submit">
    </form>
</div>

JS:

var dialogTest = $("#popup-form-test").dialog({
        autoOpen: false,
        modal: true,
        close: function () {
            console.log('closed');
        }
    });

    $("#open-popup-form-test").on("click", function () {
        dialogTest.dialog("open");
    });

    $('#form-test').validate({
       debug: true,
        rules : {
            testText: {
                required: true
            }
        },
        submitHandler: function(form) {
            alert('submitted');
        }
    });
1

There are 1 answers

2
Dekron On

you must use the open callback of .dialog() and insert there the validator:

var dialogTest = $("#popup-form-test").dialog({
    autoOpen: false,
    modal: true,
    open : function (event, ui) {
      $('#form-test').validate({
        debug: true,
        rules : {
          testText: {
            required: true
          }
        },
        submitHandler: function(form) {
           alert('submitted');
        }
      });
    },
    close: function () {
        console.log('closed');
    }
});

i can't test without a valid example but it should work.