duyvu1311
duyvu1311

Reputation: 97

Jquery Validate on dynamic form

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!

Upvotes: 0

Views: 1891

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337550

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();
});

Upvotes: 1

Related Questions