0

I use Jquery validation (http://jqueryvalidation.org) to validate form. My code:

<div id="form-section"></div>
<button id="add-form" type="button">Add form</button>

<script>
    $(document).ready(function () {
        $('#add-form').click(function () {
            $('#form-section').html('<form id="myform"> <input type="email" name="email" placeholder="Email" required> <input type="password" name="password" placeholder="Password" required> <button type="submit">Submit</button> </form>');
        });

        $('#myform').validate();
    })
</script>

But $('#myform').validate(); not working. How can I validate a dynamic form like this? Thanks!

duyvu1311
  • 97
  • 2
  • 11

1 Answers1

1

The #myform element doesn't exist in the DOM when you first call validate(). Instead, place that line within the click() handler, after the form is created:

$('#add-form').click(function () {
    $('#form-section').html('<form id="myform"> <input type="email" name="email" placeholder="Email" required> <input type="password" name="password" placeholder="Password" required> <button type="submit">Submit</button> </form>');
    $('#myform').validate();
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Yes, this work fine, but is there any way to use it with jQuery .on() function, such as $('#form-section').on() ?. – duyvu1311 Oct 21 '15 at 09:57
  • I'm not sure what you mean. `on()` relates to an event handler, which you already have in the form of `click()`. – Rory McCrossan Oct 21 '15 at 09:59
  • I dont know if Jquery Validate supports an event like 'submit' event. Example: $('#form-section').on('validate', '#myform', function(){ // some code }); – duyvu1311 Oct 21 '15 at 10:06
  • If you want to run some code when the `validate()` method is called use the events it provides in the optional parameters. Check their documentation for more information. – Rory McCrossan Oct 21 '15 at 10:08